[C/C++] 算法提高 质因数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Selukwe/article/details/78546279

将一个正整数N(1 < N < 32768)分解质因数。
例如,输入90,打印出 90=2*3*3*5。
样例输入
66
样例输出
66=2*3*11

#include <iostream>
using namespace std;

int main ()
{
    int a;
    int sum = 1;
    int i = 1;

    // 设置一个标志,判断是不是第一个数字。是的话不用输出*号。 
    int flag = 1;

    cin >> a;
    cout << a << "=";

    int b = a; // 用来存放原数字 

    while (sum != b)
    {
        i++;
        if (a % i == 0)
        {
            if (flag)
            {
                cout << i;
                flag = 0;
            }
            else
                cout << "*" << i;
            a = a / i;
            sum *= i;
            i--; //下一个可质因素能跟前一个重复,比如45=3*3*5,第二个等于第一个,先减一再加一,还是上一个i。 
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Selukwe/article/details/78546279
今日推荐