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.
#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!
elsereturn -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!
elsereturn -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 . . .
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.