[英]Return prime factors from int as input as an array
我需要編寫一個算法,它接受一個int
,獲取它的主要因素,將它們放入一個數組中並返回它們。
我的代碼如下。
public static int[] primfaktorzerlegung(int zahl) {
int d=1; //this is the length of the array
int[] result = new int[d]; //array has to be returned
List<Integer> factors = new ArrayList<Integer>();
for(int factor = 2; factor <= zahl; factor++) {
while(zahl % factor == 0) {
factors.add(factor);
zahl = zahl / factor;
}
}
for(int i : factors){ //trying to get every number of the arraylist
int z = i;
result[d] = z; //trying to put the numbers of the arraylist into the array result
d++; //makes the array dimension one higher
}
return result; //returns the array
}
我收到以下錯誤:
Error: java.lang.ArrayIndexOutOfBoundsException:
Index 1 out of bounds for length 1
at: result[d] = z;
可能是什么原因?
您實際上並沒有通過增加d
來增加數組的大小。 一旦分配了數組,它的大小就固定了。
你可以這樣做:
public static int[] primes(int number) {
List<Integer> factors = new ArrayList<>();
for(int factor = 2; factor <= number; factor++) {
while (number % factor == 0) {
factors.add(factor);
number = number / factor;
}
}
return factors.stream().mapToInt(n -> n.intValue()).toArray();
}
stream()
方法將ArrayList
公開為Stream
,這允許您使用不錯的方法來操作集合。 其中之一是mapToInt
,它允許您mapToInt
中的每個元素應用一個函數。 您應用接受n
並返回正文中的任何內容( ->
之后的部分)的函數。 特別是,由於您將一組裝箱的Integer
放在一起,因此您必須將它們拆箱到int
(更多關於裝箱的內容請點擊此處)。 intValue()
方法正是這樣做的。 最后,通過調用toArray()
返回一個int[]
。 實際上,您是說:將intValue()
應用於列表中的每個項目並返回結果數組。
請注意,我按原樣接受了您的主要邏輯,我沒有討論您如何計算主要因素的正確性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.