日期:2014-05-20  浏览次数:20691 次

求一个数的素数因子!
怎么求一个数的素因子
比如:12=2*2*3 20=2*2*5

------解决方案--------------------
首先有一个素数集合{2,3,5,7,...}
然后对这个数从小到大分解,也就是从2开始整除,循环直到2不能整除,然后下一个素数,一直到商也是一个素数,其实这时候应该是商等于一个素数时结束
------解决方案--------------------
没找到java的,只给给你个参考,还有素因子可以重复的吗?我不清楚..
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

bool IsPrime(const int num)
{
int sqt = sqrt(num);
for (int i=2; i<=sqt; i++){
if (num % i == 0)return false;
}
return true;
}

void GetPrimeFactorial(const int num)
{
int sqt = sqrt(num);
for (int i=2; i<=sqt; i++){
if (num%i==0 && IsPrime(i))
cout << setw(5) << i;
}
if(IsPrime(num)) cout << setw(5) << num;
cout << endl;
}

void main()
{
unsigned int n; //5*7*29*4*36=146160
cout << "Input a number(such as 146160): ";
cin >> n;
GetPrimeFactorial(n);
}

运行示例:
Input a number(such as 146160): 140160
2 3 5 73
Press any key to continue

------解决方案--------------------
探讨
首先有一个素数集合{2,3,5,7,...}
然后对这个数从小到大分解,也就是从2开始整除,循环直到2不能整除,然后下一个素数,一直到商也是一个素数,其实这时候应该是商等于一个素数时结束