Greatest Common Divisor from a set of more than 2 integers

后端 未结 13 1021
遇见更好的自我
遇见更好的自我 2020-12-09 04:25

There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function

13条回答
  •  抹茶落季
    2020-12-09 05:03

    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); 
        } 
    

提交回复
热议问题