Sunday, August 2, 2009

Lcm gcd program with recursive function in c language?

Hi I'm not exactly remembering the algorithm. I think its like this.





int gcd(int a, int b)


{


int g;


if(b==0)


g=a; //if b=0 then gcd will be a


else


{


if(b%26gt;a)


swap(a,b);


else


a=a%b;


g=gcd(b,a);


}


return g;


}





For example a=40 and b=16





Level 1:


a=8 b=16 // after a = a%b. Now we are calling gcd(16,8)





Level 2:


a=0 b=8 // after a = a%b. Now calling gcd(8,0)





Level 3:


Now b==0 and hence gcd will be 8.





Now you can find the lcm from the formula gcd*lcm = a*b





Yeah for lcm, lcm = (a*b)/gcd





Is it enough!


No comments:

Post a Comment