题解 | #质数因子#

质数因子

https://www.nowcoder.com/practice/196534628ca6490ebce2e336b47b3607

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

bool isPrime(int n) {
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

int nextPrime(int n, int max) {
    for (int i = n + 1; i <= max; i++) {
        if (isPrime(i)) {
            return i;
        }
    }
    return max;
}

int main() {
    int a;
    while (cin >> a) { // 注意 while 处理多个 case
        int factor = 2;
        while (!isPrime(a)) {
            if (a % factor == 0) {
                cout << factor << ' ';
                a = a / factor;
            } else {
                factor = nextPrime(factor, a);
            }
        }
        cout << a << ' ';
    }
    return 0;
}
// 64 位输出请用 printf("%lld")
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务