This is a blog for interview questions. The questions are primarily from certain web forums, BBS or books. The owner of this blog doesn't claim any copyright of those questions. The blog is established primarily to help the blog owner prepare job interviews.
Thursday, March 1, 2012
Find the Greatest Common Divisor (GCD)
Problem: Given two non-negative integer a and b, find the greatest common divisor.
Solution: A very efficient algorithm is Euclid’s algorithm. The main idea here is GCD(a, b) = GCD(b, a mod b). Therefore, the code is straightforward:
int GCD(int a, int b)
{
if(b==0) return a;
return GCD(b, a mod b);
}
No comments:
Post a Comment