我正在嘗試使用Eratosthenes的Sieve方法來查找大數的最大素數因子(Project Euler中的問題3)。Project Euler prob。 3 IndexOutOfBoundsException
我的語法似乎是正確的,我用龍(不是int),但我發現了以下錯誤消息:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at problem3.ProblemThree.Factor(ProblemThree.java:49)
at problem3.ProblemThree.Recursion(ProblemThree.java:37)
at problem3.ProblemThree.main(ProblemThree.java:83)
我不知道爲什麼會這樣。有人能告訴我我在做什麼錯嗎?
package problem3;
import java.util.List;
import java.util.ArrayList;
public class ProblemThree
{
//initializing variables and lists
long factorNo;
long nowTesting;
int i;
List<Long> allPrimeList = new ArrayList<Long>();
List<Long> ourPrimes = new ArrayList<Long>();
ProblemThree(long x) //constructor; the input "x" is the number whose highest prime factor is being sought
{
factorNo = x;
}
void initialize() //use the workaround initialization (add 2 to the allPrimesList, set nowTesting to 3).
//If the factorNo is even, add 2 to the primes list
//TODO: need more elegant solution
{
allPrimeList.add((long) 2);
nowTesting=3;
if(factorNo % 2 == 0) ourPrimes.add((long) 2);
i = 0;
}
void recursion() //keep factoring the next nowTesting until the next nowTesting is greater than half of the factorNo
{
while (nowTesting <= (factorNo/2))
{
nowTesting = factor(nowTesting);
}
System.out.println(ourPrimes);
}
long factor(long t) //The factorization algorithm. Lists all the factors of long t
{
nowTesting = t;
// Line 49:
if ((nowTesting % allPrimeList.get(i)) == 0)
{
i = 0;
return (nowTesting + 2);
}
else
if(i <= allPrimeList.size()) //if we have not yet reached the end of ourPrimeList
{
i++;
return nowTesting;
}
else //if the end of ourPrimeList has been reached without a single modulus==0, this number is a prime
{
allPrimeList.add(nowTesting);
if(factorNo%nowTesting==0) //if the nowTesting is a prime factor of factorNo, it will be perfectly divisible
{
ourPrimes.add(nowTesting);
}
i=0;
return (nowTesting+2);
}
}
public static void main (String[] args)
{
ProblemThree pt = new ProblemThree(600851475143L);
pt.initialize();
pt.recursion();
}
}
您是否嘗試過查找這些錯誤消息的含義? – simchona 2012-04-15 01:40:26
爲了讓你知道,方法名稱習慣使用'camelBack'和類來使用'CapitalizedWords'。當你的方法名稱看起來像類時,解析代碼是非常困難的。 – 2012-04-15 01:44:38
根據錯誤消息,在第49行,當它只有1個項目時(索引爲0),將從'allPrimeList'數組的索引1中獲取項目。這是一個錯誤。所以你需要回顧一下你的邏輯,並確定你爲什麼試圖訪問超出數組末尾的索引。 – ulmangt 2012-04-15 01:44:42