Concept: What is GCD?
The GCD (Greatest Common Divisor) of two numbers is the largest positive integer that divides both numbers without leaving a remainder.
Example
Numbers: 20 and 30
Divisors of 20: 1, 2, 4, 5, 10, 20
Divisors of 30: 1, 2, 3, 5, 6, 10, 15, 30
GCD = 10
Formula (Using Euclid’s Algorithm)
GCD(a, b) = GCD(b, a % b)
When b = 0, then GCD(a, b) = a
Step 1: Design Page – GCDExample.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GCDExample.aspx.cs" Inherits="GCDExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Find GCD using C# WebForms</title>
<style>
body {
font-family: Arial;
background-color: #f4f7fc;
margin: 50px;
}
.container {
width: 500px;
margin: auto;
background: #fff;
border-radius: 10px;
box-shadow: 0 0 10px #ccc;
padding: 25px;
}
h2 {
text-align: center;
color: #1A2A80;
}
.form-control {
width: 100%;
padding: 8px;
margin-top: 10px;
}
.btn {
background-color: #7A85C1;
color: white;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
width: 100%;
margin-top: 15px;
}
.btn:hover {
background-color: #5b68a1;
}
.result {
margin-top: 20px;
font-weight: bold;
color: #333;
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>Calculate GCD (Greatest Common Divisor)</h2>
<asp:Label ID="lblNum1" runat="server" Text="Enter First Number:"></asp:Label><br />
<asp:TextBox ID="txtNum1" runat="server" CssClass="form-control" placeholder="Example: 20"></asp:TextBox><br />
<asp:Label ID="lblNum2" runat="server" Text="Enter Second Number:"></asp:Label><br />
<asp:TextBox ID="txtNum2" runat="server" CssClass="form-control" placeholder="Example: 30"></asp:TextBox><br />
<asp:Button ID="btnCalculate" runat="server" Text="Find GCD" CssClass="btn" OnClick="btnCalculate_Click" /><br />
<asp:Label ID="lblResult" runat="server" CssClass="result"></asp:Label>
</div>
</form>
</body>
</html>
Step 2: Backend Code – GCDExample.aspx.cs
using System;
public partial class GCDExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCalculate_Click(object sender, EventArgs e)
{
try
{
int num1 = Convert.ToInt32(txtNum1.Text.Trim());
int num2 = Convert.ToInt32(txtNum2.Text.Trim());
if (num1 <= 0 || num2 <= 0)
{
lblResult.Text = "Please enter positive numbers only.";
lblResult.ForeColor = System.Drawing.Color.Red;
return;
}
int gcd = FindGCD(num1, num2);
lblResult.Text = "GCD of " + num1 + " and " + num2 + " is: " + gcd.ToString();
lblResult.ForeColor = System.Drawing.Color.Green;
}
catch
{
lblResult.Text = "Invalid input! Please enter valid integers.";
lblResult.ForeColor = System.Drawing.Color.Red;
}
}
// Recursive function to find GCD
private int FindGCD(int a, int b)
{
if (b == 0)
return a; // Base case
else
return FindGCD(b, a % b); // Recursive case
}
}

Join the conversation! Your thoughts help the community grow.