GCD (greatest common divisor) and LCM (least common multiple)

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int gcd (int a, int b){
	if (a == 0) return b;
	else 	if (b == 0) return a;
		else 	if (a > b) return gcd (b, a);
			else return 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;
	}
}
Last edited on
Updated post
> 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

a*b / gcd = (a*b/gcd) * gcd/gcd = (a/gcd) * (b/gcd) * gcd

also, unsigned
Last edited on
Thanks for your explanation, it worked
Topic archived. No new replies allowed.