最低公倍数的c ++循环

时间:2014-12-11 11:32:10

标签: for-loop lcm

我在执行此任务时遇到一些问题:您读取舞会文件“perechi.in”的数字n,您必须在文件“perechi.out”中写入多少对数字的LCM等于n。我写了那段代码,但它崩溃了,我找不到问题

 #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 个答案:

答案 0 :(得分:1)

您的代码中存在两个逻辑错误

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

尝试以下代码

#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;
}