Function help

I have been working of a LCM Calculator.
I decided to use a function in this program.
Here is the Function code:
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
//LCM Function
int LCM (int num1,int num2)
{
	//Variable:
	int lcm;
	int factor1;
	int factor2;
	int multiplier1 = 1;
	int multiplier2 = 1;
	int lcmultiple;
	
	do
	{
		multiplier1 = multiplier1 + 1;
		multiplier2 = multiplier2 + 1;
		
		factor1 = num1*multiplier1;
		factor2 = num2*multiplier2;
		
	}while (factor1 < factor2, factor1 > factor2);
	
	
	lcmultiple = factor1 = factor2;
	
	return lcmultiple;
}


But the program fails to calculate the value properly. (for instance, it gave me the LCM of 8 and 15 is 30)

I can't understand what is causing this error. Any help?
Last edited on
while (factor1 < factor2, factor1 > factor2);
does not what you think it does. I think what you mean is
while (factor1 != factor2);
Anyway, your 'algorithm' will never calculate the LCM because if num1 does not equal num2 factor1 will never equal factor2. If they are equal it will return 2*num1.
I initially tried the != operator. But the program didn't give any result apart from 0. And it took a very long time in doing so. Hence I tried changing it to the current version.
Any help on how could I correct this problem?

Last edited on
Are you just going to check all multiples of num1 and num2?
In that case you should pick the larger one and for each of it's multiples, check if it is also a multiple of the smaller one.

One problem with your code is line 20. When you separate two things with a comma, only the return value of the second one matters. What you wanted is ||. What you need is factor1 != factor2.
Also, line 23 is silly. It sets factorial1 and lcmultiple both to factorial2. factorial1 is already equal to factorial2 at this point though.

If I understand your intentions correctly, what you wanted to write is a loop where factor1 and 2 are incremented until they are equal. The problem is that every time factor 1 grows, so does factor 2. You should only add to factor 1 is it is smaller than 2 and vice versa.

Though I think it would be faster to use the fact that lcm(a,b) = a*b/gcd(a,b). gcd isn't hard to compute. I believe there is some pseudo code in wikipedia, if you're interested.
O.K. Thanks. I had completely forgotten about that formula and that's why adopted the longer method. I will try to make the program now. Thanks again for the help.

EDIT: Program made successfully. Thanks a lot, again, for the help and those correction in my methods.
Last edited on
Topic archived. No new replies allowed.