c++ loop for lowest common multiple

694 Views Asked by At

I have some problems with this task: you read prom file "perechi.in" a number n and you have to write in a file "perechi.out" how many pairs of numbers have the LCM equal with n. I wrote that code but it crashes and i cannot find out the issue

 #include <iostream>
    #include <fstream>

using namespace std;

int main()
{
    int a, b, c, ca, cb, i = 0, n;
    ifstream f("perechi.in");
    ofstream g("perechi.out");
    f >> n;
    for (a = 1; a<n; a++){
        for (b = 1; b<n; b++){
            ca = a;
            cb = b;
            c = ca%cb;

            while (c>0){
                ca = cb;
                cb = c;
                c = ca%cb;
            }
            if (ca*cb / c == n){
                i++;
            }
        }
    }
    g << i << "\n";
    f.close();
    g.close();
    return 0;
}
1

There are 1 best solutions below

2
On BEST ANSWER

You have two logical mistakes in your code

1) while 2) if (ca*cb / c == n){

Try the following code

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int a, b, c, ca, cb, i = 0, n;
    ifstream f("perechi.in");
    ofstream g("perechi.out");
    f >> n;
    for (a = 1; a<=n; a++){
        for (b = 1; b<=n; b++){
            ca = a;
            cb = b;
            c = ca%cb;

            if (c>0){
                ca = cb;
                cb = c;
                c = ca%cb;
            }
            if (ca*cb  == n){
                i++;
            }
        }
    }
    g << i << "\n";
    f.close();
    g.close();
    return 0;
}