我想将大数分解为素数因子。要做到这一点即时通讯使用我的版本的埃拉托色尼筛(基本上我每天保持数的最小素因子的范围内,在阵列)将长数字分解为素数因子
protected final static int PowOf2= 21;
protected final static int[] Sieve = new int[(int) Math.pow(2,PowOf2)];
protected final static int range = (int) Math.pow(2,PowOf2); //range of long types
static int a=0; //counter
public static void init(long n){
for(int i=0; i<range-1; i++){
Sieve[i]=i; //at first every number is equal to it's index
}
for(int i = 2; i*i <= range-1; i++)
{
if (Sieve[i] == i){
for (int j = 2 * i ; j <= range-1; j += i)
{
Sieve[j] = i; //after that every number(index) has a smallest prime factor assigned to it
}
}
}
}
然后我用这个数组来给出数除以以素因子
的public static long[] intoPrimeFactors (long n){
long[] array = new long[range-1];
while(!isPrime(n)){
array[a]=Sieve[(int)n]; //here's an error
n/=Sieve[(int) n];
a++;
}
array[a]=n;
return array;
}
在主我printig了所有的因素
public static void main(String[] args){
long n=new Long(args[0]);
init(Math.abs(n));
long[] array = intoPrimeFactors(Math.abs(n)); //here's an error
System.out.print(n+" = ");
if(n<0){
n=Math.abs(n);
System.out.print("-1*");
}
for(int i=0;i<=a;i++){
if(i!=a)System.out.print(array[i]+"*");
else System.out.print(array[i]);
}
}
而且它适用于小数字(INT),但是当我在类似9223371331键入我得到ArrayOutOfBo就好了和错误(在函数主要和intoPrimeFactors),我不知道为什么。你可以帮帮我吗 ?
您可能需要使用BigInteger http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html – Steephen
你正在采取一个“长'并投射到一个'int'。在这之后你不应该指望什么。 – Teepeemm