1

Inbuilt __gcd() function is not working on Xcode macOS. I have run the following code on Xcode (macOS Catalina) it shows an error "Use of undeclared identifier '__gcd' ".

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    cout << "gcd(6, 20) = " << __gcd(6, 20) << endl;
    return 0;

}

please help me out

4 Answers4

4

You can use the one from <numeric> if you compile with -std=c++17

#include <numeric>

int main()
{
    std::cout << "gcd(6, 20) = " << std::gcd(6, 20) << std::endl;
    return 0;
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

Thanks for asking,
Use the following function below header files, as gcd is not working in mac m1:

int __gcd(int a, int b) { 
    if (b == 0) { 
        return a; 
    } 
    return gcd(b, a % b); 
}

Then you can use __gcd(a, b) function easily and efficiently.

nobleknight
  • 755
  • 6
  • 15
0

std::gcd() is available in c++17

otherwise,

The GCD for two non negative integers is easily calculated:

int gcd(int a, int b){ int c = a % b; while(c != 0) { a = b; b = c; c = a % b; } return b;}

cf. https://www.gamedev.net/forums/topic/358629-built-in-c-command-for-gcd/3354131/

Richard Barber
  • 5,257
  • 2
  • 15
  • 26
0

Some answers, here, contain Euclidean based code for calculating gcd. For example :

int gcd(int a, int b) { if(b == 0){return a;} return gcd(b, a % b); }

You will have to take care about the order of actual arguments you pass to this function. Code is based on assumtion that a>0, b>0 and a>=b.

Code can be modified to remove these assumptions.

int gcd(int a,int b)
{
    if(a<0 or b<0)
        return -1;
    
    if(a>b)
        return gcd(b,a);
    
    if(a==0)
        return b;
    
    //Due to Euclidean algorithm
    return gcd(a,b%a); 
}

If you stick to first version, you will have to take care about sending arguments according to the above assumptions.