C# find the greatest common divisor

后端 未结 9 1494
夕颜
夕颜 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:34

    If efficiency is not a big concern this will do the job.

    // gets greatest common divisor of A and B. 
    var GCD=Enumerable.Range(1,Math.Min(A,B)).Last(n=>(A%n | B%n)==0);
    
    0 讨论(0)
  • 2020-12-02 23:35

    Using LINQ's Aggregate method:

    static int GCD(int[] numbers)
    {
        return numbers.Aggregate(GCD);
    }
    
    static int GCD(int a, int b)
    {
        return b == 0 ? a : GCD(b, a % b);
    }
    

    Note: answer above borrowed from accepted answer to Greatest Common Divisor from a set of more than 2 integers.

    0 讨论(0)
  • 2020-12-02 23:36

    Try this:

    public static int GCD(int p, int q)
    {
        if(q == 0)
        {
             return p;
        }
    
        int r = p % q;
    
        return GCD(q, r);
    }
    
    0 讨论(0)
  • 2020-12-02 23:38
        int a=789456;
    
    
        int b=97845645;
        if(a>b)     
        {
    
        }
        else
        {
            int temp=0;
            temp=a;
            a=b;
            b=temp;
        }
        int x=1;
        int y=0 ;
    
        for (int i =1 ; i < (b/2)+1 ; i++ )
        {
    
            if(a%i==0)
            {
                 x=i;
            }
            if(b%i==0)
            {
                 y=i;
            }
            if ((x==y)& x==i & y==i & i < a)
            {
                Console.WriteLine(i);
            }
    
        }
    
    0 讨论(0)
  • 2020-12-02 23:45

    You can try using this:

    static int GreatestCommonDivisor(int[] numbers)
    {
        return numbers.Aggregate(GCD);
    }
    
    static int GreatestCommonDivisor(int x, int y)
    {
    return y == 0 ? x : GreatestCommonDivisor(y, x % y);
    }
    
    0 讨论(0)
  • 2020-12-02 23:45
    By using this, you can pass multiple values as well in the form of array:-
    
    
    // pass all the values in array and call findGCD function
        int findGCD(int arr[], int n) 
        { 
            int gcd = arr[0]; 
            for (int i = 1; i < n; i++) {
                gcd = getGcd(arr[i], gcd); 
    }
    
            return gcd; 
        } 
    
    // check for gcd
    int getGcd(int x, int y) 
        { 
            if (x == 0) 
                return y; 
            return gcd(y % x, x); 
        } 
    
    0 讨论(0)
提交回复
热议问题