Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all
how the Greatest common divisor 2 number in c#?
Posted
Updated 20-Feb-12 23:35pm
v2
Comments
Andreas Gieriet 21-Feb-12 5:33am    
So you ask for something like int gcd = Gcd(a, b);?

If you know the algorithm, the solution is straight forward. It's an exercise in recursive or iterative programming of a recursive problem.

And if you just want to get any implementation, ask google, e.g. c# math.gcd
Varun Sareen 21-Feb-12 5:34am    
have you tried something earlier or not? try try and try until you succeed.

Google is your friend: c# math.gcd
 
Share this answer
 
Comments
Varun Sareen 21-Feb-12 5:37am    
good one..People here are so lazy to search on google. They just want to get their work done from others :P
 
Share this answer
 
Comments
Varun Sareen 21-Feb-12 5:37am    
hahaha!!! good one superb
C#
using System;

public class Program
{
    static int GCD(int a, int b)
    {
        int Remainder;

        while( b != 0 )
        {
            Remainder = a % b;
            a = b;
            b = Remainder;
        }

        return a;
    }

    static int Main(string[] args)
    {
        int x, y;

        Console.WriteLine("This program allows calculating the GCD");
        Console.Write("Value 1: ");
        x = int.Parse(Console.ReadLine());
        Console.Write("Value 2: ");
        y = int.Parse(Console.ReadLine());

        Console.Write("\nThe Greatest Common Divisor of ");
        Console.WriteLine("{0} and {1} is {2}", x, y, GCD(x, y));

        return 0;
    }
}
 
Share this answer
 
Comments
Andreas Gieriet 21-Feb-12 5:56am    
Or recursively:

public static int Gcd(int a, int b)
{
return b == 0 ? a : Gcd(b, a%b);
}
Mohammad A Rahman 21-Feb-12 6:07am    
Nice One :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900