题解 | #质因数的个数#
质因数的个数
https://www.nowcoder.com/practice/20426b85f7fc4ba8b0844cc04807fbd9
方法一:对于每个输入都通过遍历方式寻找质因数
#include <stdio.h> #include <cmath> int main() { int s,i,count; while(scanf("%d",&s)!=EOF) { count=0; int bound=sqrt(s); for(i=2;i<=bound;i++) { while(s%i==0) { count++; s=s/i; } } if(s>1) printf("%d\n",count+1); else printf("%d\n",count); } return 0; }
方法二:首先通过一维数组筛选出全部素数
#include <initializer_list> #include <iostream> #include "vector" #include "cmath" using namespace std; int main() { int N; int MAXN = sqrt(1e9) + 1; vector<int> prime; bool isPrime[MAXN]; for (int i = 0; i < MAXN; i++) { isPrime[i] = true; } isPrime[0] = isPrime[1] = false; for (int i = 2; i < MAXN; i++) { if (!isPrime[i]) { continue; } prime.push_back(i); for (int j = i * i; j < MAXN; j += i) { isPrime[j] = false; } } while (cin >> N) { // 注意 while 处理多个 case // cout << a + b << endl; int num = 0; for (int i = 0; i < prime.size() && prime[i] < N; i++) { int zys = prime[i]; while (N % zys == 0) { N /= zys; num++; } } if (N > 1) num++; cout << num << endl; } } // 64 位输出请用 printf("%lld")