-1

I tried making a program to find the lowest common multiple of any two numbers. I have gotten most of the way there but my program prints all of the common multiples from 1-1000000 instead of just the first one. How do I make it print only the first one ?

#include <iostream>
using namespace std;

int main() {
    cout << "Find the lowest common multiple of two numbers, just enter them one after the other" << endl;
    int firstNum;
    int secondNum;
    cin >> firstNum;
    cin >> secondNum;
    int i;

    for (i = 1; i < 1000001; i++) {

        if (i % firstNum == 0 && i % secondNum == 0) {

            cout << "these two number's LCM is" << i << endl;
        }
    }



    system("pause");
    return 0;

}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • Just add a `break` after `cout << "these two number's LCM is" << i << endl;` – DimChtz Jul 12 '16 at 14:16
  • [`break;`](http://en.cppreference.com/w/cpp/language/break). Also, please reconsider your use of what are often considered bad practices: [`using namespace std;`](http://stackoverflow.com/q/1452721/1171191) and [`endl`](http://chris-sharpe.blogspot.co.uk/2016/02/why-you-shouldnt-use-stdendl.html) (those are links to explanations). – BoBTFish Jul 12 '16 at 14:16

3 Answers3

1

You can add a break to end a loop. In your case, you want to add it at the end of your if statement:

for (i = 1; i < 1000001; i++) {
    if (i % firstNum == 0 && i % secondNum == 0) {
        cout << "these two number's LCM is" << i << endl;
        break;
    }
}
Simon
  • 774
  • 4
  • 21
0

Your problem is a break statement as others have mentioned.

But a better solution: lcm is standardized in C++17! So you can just do:

cout << lcm(firstNum, secondNum) << endl;

If you don't have access to C++17 yet this is already available in the namespace experimental: http://en.cppreference.com/w/cpp/experimental/lcm

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
0

After finding the first one you need to leave from for loop, that is why it keeps printing other values.

for (i = 1; i < 1000001; i++) {

if (i % firstNum == 0 && i % secondNum == 0) {
    cout << "these two number's LCM is" << i << endl;
    break;
}

}

4JaoDeka
  • 43
  • 1
  • 1
  • 6