用双循环分解数字

Factoring Numbers with a Double Loop

本文关键字:数字 分解 双循环      更新时间:2023-10-16

问题&示例:http://prntscr.com/atfkmo

以下解决方案接收到错误的输出:http://prntscr.com/atfm5w

int main() 
{
int n;
int f = 1;
cout << "Enter an integer: ";
cin >> n;
for (int i = 1; i <= n; i++)   // 1st loop to get list of numbers from 1-n.
{
    cout << "| " << i << ": ";
    while (f <= i) {      // 2nd loop to get list of factors for each number from 1-n
        if (i%f == 0)     // divisibility check
        {
            cout << f;
        }
        f++;
    }
    cout << endl;
}

我已经破解了将近一个小时,以至于我不再理解这个代码的逻辑。如果有人能解决这个问题或向我解释有缺陷的代码的逻辑,我将不胜感激。

您需要为每个数字重新初始化值f=1

int main() 
{
    int n;
    int f = 1;
    cout << "Enter an integer: ";
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        f=1;                          //   reinitialize
        cout << "| " << i << ": ";
        while (f <= i) {
        if (i%f == 0)
        {
            cout << f;
        }
        f++;
        }
        cout<<"n";
    }
    cout << endl;
}

https://ideone.com/KvFFDf