题解 | #质因数的个数#
质因数的个数
https://www.nowcoder.com/practice/20426b85f7fc4ba8b0844cc04807fbd9
#include <iostream> #include<math.h> #include<vector> using namespace std; //判断是否为素数 bool isSuNum(int x) { if (x == 2 || x == 3) { return true; } else { for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) { return false; } } return true; } } int main() { int x; while (scanf("%d", &x) != EOF) { int count = 0; vector<int> SuVec; //将素数装入SuVec中 if (x == 2) { SuVec.push_back(2); } else if (x == 3) { SuVec.push_back(2); SuVec.push_back(3); } else { for (int j = 2; j <= sqrt(x); j++) { if (isSuNum(j)) { SuVec.push_back(j); } } } //test // for (int i = 0; i < SuVec.size(); i++) { // cout << SuVec[i]; // } // printf("\n"); //-------------------------------------- for (int j = SuVec.size() - 1; j >= 0; j--) { while (x % SuVec[j] == 0) { x /= SuVec[j]; count++; } } //!!! if (x != 1) count++; //!!!如果最后结果不为1,则表明有个比sqrt(x)大的因子 cout << count; } }