I have been trying to make a program that given "n" which is followed by n positive natural numbers has to output the LCM greater than zero.
I have been given some samples to try if my program works and the program outputs the incorrect result in this one:
2 2000000 3000000 -> 6000000 (program outputs -69 "No idea why it prints -69" Probably because numbers are too big)
Can only use iostream and string library
Can only use this variables: int, double, bool, char, string (long long and others not allowed)
#include <iostream>
usingnamespace std;
int gcd (int a, int b){
if (a == 0) return b;
elseif (b == 0) return a;
elseif (a > b) return gcd (b, a);
elsereturn gcd (a, b%a);
}
int lcm (int a, int b) {
return (a*b)/gcd (a, b);
}
int main () {
int n, lcm_result, a, b;
while(cin >> n and n != 0) {
cin >> a;
lcm_result = a;
for(int i = 1; i < n; ++i) {
cin >> b;
lcm_result = lcm (b, lcm_result);
}
cout << lcm_result << endl;
}
}
> Probably because numbers are too big
the numbers are quite small, their product is too big.
you may avoid overflow by multiplying and dividing by gcd