我想將大數分解爲素數因子。要做到這一點即時通訊使用我的版本的埃拉托色尼篩(基本上我每天保持數的最小素因子的範圍內,在陣列)將長數字分解爲素數因子
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