我一直在掙扎幾個小時,以消除我不明白的錯誤。 在下面的代碼(int s = n [0])的第190行中,我得到一個數組超出範圍的異常,因爲我縮小了與數組e的關係。數組e在下面給出的代碼頂部被聲明爲對象列表a(a.size())的長度/大小,如果我用任意整數替換大小(例如10),錯誤消失。爲什麼我不能將list.size設置爲我的整型數組的長度?
爲什麼我不能將a.size設置爲我的數組長度?有沒有辦法解決這個問題?
代碼摘要:powerize(int n)應該將數字n寫爲具有最大指數的冪。因子分解將數字分解爲素數的乘積,並且gcd返回整數數組的最大公約數。
public static Power powerize(int n) throws IllegalArgumentException {
List<Power> a = MathStuff.factorize(n); //make a list of Power objects from factorize n
int size = a.size();
int[] e = new int[size];
int[] b = new int[size];
for (int i = 0; i < size; i++) { //collect all the base and exponent of each object in a. This LOOP 1
if(i >= a.size() || i >= e.length || i > b.length){System.out.print("Out of bounds in LOOP 1");} //test for out of bounds
e[i] = a.get(i).exponent;
b[i] = a.get(i).base;
}
int g = gcd(e);
int h = 1; //endproduct base
for (int i = 1; i < b.length; i++) { //Construct the base by taking the product of each base with its exponent divided by g.
if(i >= e.length || i >= b.length){System.out.print("Out of bounds in LOOP 3");} //test for out of bounds
h *= MathStuff.power(b[i], e[i]/g);
}
return new Power(h, g); //replace 2
}
/**
* factorize n
*
* @param n the number to 'powerize'
* @modifies none
* @pre {@code 2 <= n}
* @return factorization of n
*/
public static List<Power> factorize(int n) {
List<Integer> f = new ArrayList<Integer>(); // f are factors
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
f.add(i);
n /= i;
}
}
//return f; //returns factors
List<Power> p = new ArrayList<Power>(); // p are the factors with powers
for (int j = 2; j <= n; j++) { //j will be the base
int e = 0; //exponent
for (int k = 0; k <= f.size(); k++) {
if (f.get(k) == j) {
e++;
}
}
p.add(new Power(j, e));
}
return p; //returns factors in powered form
}
/**
* gcd returns the greatest common divisor of an integer array
* @param n
* @return greatest common divisor
*/
public static int gcd(int... n) {
//------------------------------------------------THE ERROR OCCURS HERE
int s = n[0];
for (int i = 1; i < n.length; i++) {
if (n[i] < s) {
s = n[i];
}
}
while (s > 1) {
int counter = 0;
int modTot = 0;
while (counter < n.length) {
modTot += n[counter] % s;
counter++;
}
if (modTot == 0) {
return s;
}
s--;
}
//return 0 if there is no gcd
return 0;
}
顯然你用一個零長度數組調用'gcd';這意味着'e'是零長度,這意味着'MathStuff.factorize'返回一個零長度列表。 –
顯然,但我找不到原因。我聲明瞭長度爲a.size()的整數數組,儘管沒有提供大小爲0的對象列表a,但我的所有測試用例都失敗了。 –
因此,在調用'factorize'之後立即檢查'a.size()> 0'。如果檢查失敗,這是'factorize'的問題。 –