分解质因子
1,用质数筛选法确定一定范围内所有质数
2.用质数对该数进行质数分解
#include<vector>
#include <iostream>
#include<cmath>
using namespace std;
vector<int > p;
bool ifPrime[10000];
//质数筛选法
void isPrime()
{
for (int i = 0; i < 10000; i++)
{
ifPrime[i] = true;
}
for (int i = 2; i < 10000; i++)
{
if (ifPrime[i] )
{
p.push_back(i);
for (int j = i * i; j < 10000; j += i)
{
ifPrime[j] = false;
}
}
}
return;
}
//x质因子个数
void coutPrime(int x)
{
int answer = 0;
for (int i = 0; i < p.size(); i++)
{
int j = p[i];
if (p[i] > sqrt(x)) break;
int count = 0;
while (x % j == 0)
{
count++;
x = x / j;
cout << j << " *";
}
answer += count;
}
if (x > 0) {
cout << x;
answer = answer + 1;
}
cout << endl <<"质因子个数:"<< answer;
}
int main()
{
isPrime();
while (true) {
int x;
cin >> x;
coutPrime(x);
}
}