English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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.

2007-12-26 16:26:19 · 2 answers · asked by Anonymous in Computers & Internet Programming & Design

2 answers

#include

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", &input);
}

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

2007-12-26 21:16:47 · answer #1 · answered by msaeed33 3 · 0 0

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 :)

2007-12-26 16:33:53 · answer #2 · answered by jgoulden 7 · 0 0

fedest.com, questions and answers