Dec 25, 2008

Give an algorithm to compute GCD(Greatest Common Divisor) for two integers.

Give an algorithm to compute GCD(Greatest Common Divisor) for two integers.
This problem can be efficiently solved by Euclidean algorithm, the basic idea is, given a pair ( a, b ) , if a%b == 0, then b is the gcd,
if not, then computer another pair ( b, a%b ), continue the steps until the reminder is 0;

Int GCD(int a,int b)
{
Int temp;
If(a<b)
{
Temp=a;
A=b;
b=temp;
}
While(a%b)
{
Temp=a%b;
a=b;
b=temp;
}
Return b;
}

No comments:

Post a Comment