Skip to content

Instantly share code, notes, and snippets.

@cruxrebels
Created April 26, 2016 18:44
Show Gist options
  • Save cruxrebels/f7a0818ace471b326350ffd587fd2f9f to your computer and use it in GitHub Desktop.
Save cruxrebels/f7a0818ace471b326350ffd587fd2f9f to your computer and use it in GitHub Desktop.
Given 2 non negative integers m and n, find gcd(m, n) GCD of 2 integers m and n is defined as the greatest integer g such that g is a divisor of both m and n. Both m and n fit in a 32 bit signed integer. Example m : 6 n : 9 GCD(m, n) : 3 NOTE : DO NOT USE LIBRARY FUNCTIONS Tags: InterviewBit Math Problems https://www.interviewbit.com/problems/gr…
int Solution::gcd(int A, int B) {
//Euclid's algorithm
while(B!=0)
{
int r = A%B;
A = B;
B = r;
}
return A;
}
//Recursive one line solution
/*int Solution::gcd(int A, int B) {
//Euclid's algorithm
return B==0 ? A : gcd(B, A%B);
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment