题解 | #质数因子#
质数因子
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")

查看3道真题和解析