novatech
-
C++,
pasted
on Jan 12:
|
|
/*
find what is the smallest number that is evenly divisible by all of the numbers from 1 to 20?.
using LCM formula refer to http://en.wikipedia.org/wiki/Least_common_multiple
*/
#include <iostream>
using namespace std;
int lcm(int a,int b,int c = 0) {
if (a%b == 0) { return a; }
c = (c == 0) ? a+a : c+a;
return (c%b == 0)? c : lcm(a,b,c);
}
int main() {
int i,x=2,total;
for (i = 3;i<=20;i++) {
cout << "lcm(" << x << ","<<i<<") = " ;
x = lcm(x,i);
cout << x << endl;
}
}
|
Output:
|
|
lcm(2,3) = 6
lcm(6,4) = 12
lcm(12,5) = 60
lcm(60,6) = 60
lcm(60,7) = 420
lcm(420,8) = 840
lcm(840,9) = 2520
lcm(2520,10) = 2520
lcm(2520,11) = 27720
lcm(27720,12) = 27720
lcm(27720,13) = 360360
lcm(360360,14) = 360360
lcm(360360,15) = 360360
lcm(360360,16) = 720720
lcm(720720,17) = 12252240
lcm(12252240,18) = 12252240
lcm(12252240,19) = 232792560
lcm(232792560,20) = 232792560
|
|