C# find the greatest common divisor

后端 未结 9 1495
夕颜
夕颜 2020-12-02 23:11

\"The greatest common divisor of two integers is the largest integer that evenly divides each of the two numbers. Write method Gcd that returns the greatest common divisor o

相关标签:
9条回答
  • 2020-12-02 23:49
    public class GCD 
    {        
        public int generalizedGCD(int num, int[] arr)
        {
             int gcd = arr[0]; 
    
            for (int i = 1; i < num; i++) {
                gcd = getGcd(arr[i], gcd); 
            }
    
            return gcd; 
        }    
        public int getGcd(int x, int y) 
        { 
            if (x == 0) 
                return y; 
            return getGcd(y % x, x); 
        } 
    }
    
    0 讨论(0)
  • 2020-12-02 23:53
    List<int> gcd = new List<int>();
    int n1, n2;
    
    bool com = false;
    
    Console.WriteLine("Enter first number: ");
    n1 = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter second number: ");
    n2 = int.Parse(Console.ReadLine());
    
    for(int i = 1; i <= n1; i++)
    {
        if(n1 % i == 0 && n2% i == 0)
        {
            gcd.Add(i);
        }
    
        if(i == n1)
        {
            com = true;
        }
    }
    
    if(com == true)
    {
        Console.WriteLine("GCD of {0} and {1} is {2}.", n1, n2, gcd[gcd.Count - 1]);
    }
    Console.ReadLine();
    
    0 讨论(0)
  • 2020-12-02 23:55

    Here's an implementation of the Euclidean algorithm that returns the greatest common divisor without performing any heap allocation.

    You can substitute ulong for uint if needed. An unsigned type is used, as the technique does not work for signed values. If you know your a and b values are not negative, you can use long or int instead.

    private static ulong GCD(ulong a, ulong b)
    {
        while (a != 0 && b != 0)
        {
            if (a > b)
                a %= b;
            else
                b %= a;
        }
    
        return a | b;
    }
    

    This method is used in my metadata-extractor library, where it has associated unit tests.

    0 讨论(0)
提交回复
热议问题