题解 | #质数因子#
质数因子
https://www.nowcoder.com/practice/196534628ca6490ebce2e336b47b3607
#include<iostream>
#include <math.h>
using namespace std;
bool judge (int a);
int main(){
int input;
int c = 2;
cin >> input;
if (input == 1) cout << endl;
while (input > 1) { //除到最后input为1
if (judge(input) == true) { //判断自身是否是质数
cout << input <<" ";
break;
}
if (input % c == 0 && judge(c) == true) { //如果能被当前质数整除,c 初始是2
while (input % c == 0) { //能被当前质数除断就一直除
input /= c;
cout << c << " ";
}
//如果当前质数无法继续整除就改变质数
c++;
}
else c++; //当前质数无法整除就一直更新质数
}
}
bool judge (int a) { //判断是否是质数。·
int i ;
for (i = 2; i < (int)sqrt(a) + 1; i++) {
if (a % i == 0) return false;
}
return true;
}
第一接触质数因子这个题很懵,感觉其他大佬的解法我看不太明白,特别是有的解法没有质数判断的这个环节,所以在参考了其他解法的基础上,着重写一下质数判断的函数。
质数也就是只能被 1 和自身整除的数。 比如判断n 我们不需要遍历2到n-1 来看有没有其他数可以整除,只需遍历从2 到 sqrt(n)+ 1即可!!!具体为啥我不知道咋解释,反正效果是这样了.....
