Saturday, May 22, 2010

Can someone pleasee help me with this C programming assignment quick?

Assignment in C:





Write an efficient program that gets a list of (positive) integers from the user and then compute their Least Common Multiple (LCM). LCM of k given numbers, denoted in Mathematics as LCM (n1, n2, n3, …, nk), is the smallest (positive) integer that all the numbers n1, n2, …, nk, are their divisors. For example, LCM (2, 2) = 2, LCM (2, 4) = 4, LCM (2, 3, 4) = 12, LCM (2, 5, 8, 10) = 40, etc.











You may assume the user enters all the positive numbers and then 0 to end the input. The user may enter as many numbers as they want.





The program must be efficient.

Can someone pleasee help me with this C programming assignment quick?
#include %26lt;stdio.h%26gt;





int gcd(int a, int b) {


return (b == 0 ? a : gcd(b, a%b));


}





int lcm(int a, int b) {


return a * b / gcd(a, b);


}





int main() {


int input = 1, result = 1;





while (input != 0) {


result = lcm(input, result);


printf("Enter an integer: ");


scanf("%d", %26amp;input);


}





printf("The Least Common Multiple is %d\n", result);


return 0;


}
Reply:First you need the greatest common divisor, commonly computed recursively using Euclid's Algorithm:





int gcd(int a, int b){


  if ( b == 0 )


    return a;


  else


    return gcd (b, a%b);


}





Now the Least Common Multiple of a and b is ab / gcd(a,b).





The trivial matters of I/O are left as an exercise for the reader :)


No comments:

Post a Comment