Function Returning Wrong Value

I was just testing out my lowest common multiple (LCM) and highest common factor (HCF) functions but it returns the wrong value when I add the else statement.


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
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using std::cout; using std::cin; using std::endl;

/*Lowest Common Multiple*/
int LCM(int n1, int n2)
{
	for (int i = 1; i <= n1 * n2; i++)
	{
		if ((i % n1) == 0 && (i % n2) == 0)		//LCM has no remainder
			return i;	//found LCM!
		else 
			return -1;	//can't find LCM...
	}
}

/*Highest Common Factor*/
int HCF(int n1, int n2)
{
	for (int i = n1 * n2; i > 0; i--)
	{
		if ((n1 % i) == 0 && (n2 % i) == 0)
			return i;	//found HCF!
		else
			return -1;	//can't find HCF...
	}
}

int main()
{
	int n1 = 0, n2 = 0;

	cout << "Enter two numbers to find the lowest common multiple: ";
	cin >> n1 >> n2;
	cout << "Lowest common multiple of " << n1 << " and " << n2 << " is: " << LCM(n1, n2) << endl;

	cout << "Enter two numbers to find the highest common factor: ";
	cin >> n1 >> n2;
	cout << "Highest common factor of " << n1 << " and " << n2 << " is: " << HCF(n1, n2) << endl;
}



Enter two numbers to find the lowest common multiple: 10 20
Lowest common multiple of 10 and 20 is: -1
Enter two numbers to find the highest common factor: 10 20
Highest common factor of 10 and 20 is: -1
Press any key to continue . . .


Without the else statement it works perfectly...

Enter two numbers to find the lowest common multiple: 10 20
Lowest common multiple of 10 and 20 is: 20
Enter two numbers to find the highest common factor: 10 20
Highest common factor of 10 and 20 is: 10
Press any key to continue . . .


Does anyone know why?
Last edited on
Try removing the else parts and put return -1; after the for loop.
@Danny
Try removing the else parts and put return -1; after the for loop.

That seems to fix it, but why doesn't it work when the else is inside the for loop?
Assume the inputs are n1 = 10, n2 = 20.

The first iteration of the for loop (i = 1):
--->if ((1 % 10) == 0 && (1 % 20) == 0)
---> 1 % 10 = 1, thus the condition fails going to the else clause which returns -1

What you want to do is check every value of 1 <= i <= n1 * n2. Since the return statement is in the loop it is called on the first value of i that doesn't divide n1 or n2, thus you don't check every value of i in the range you are looking at.
Thanks.
:)
Topic archived. No new replies allowed.