我正在嘗試解決Project Euler上的Problem 12。 我有一個如何完成這個問題的想法,但是我遇到了一個 錯誤。我已經搜索瞭如何從不同的問題中使用ArrayList,但是我仍然面臨問題 。錯誤:嘗試返回ArrayList時不兼容的類型
import java.util.ArrayList;
public class Level_12 {
/*
The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
*/
public static ArrayList<Long> check(long num) {
ArrayList<Long> divisors = new ArrayList<Long>();
for (long o = 1; o <= Math.sqrt(num); o++)
if (num % o == 0) {
divisors.add(o);
System.out.println(o + " is a current divisor of " + num);
}
for (Long m : divisors) {
return m;
}
}
public static void main(String[] args) {
long triangle = 0; //Triangle number
long total = 500; //Total divisors
long currenttotal = 0; //Amount of divisors
long i = 0; //Just to itterate
while (currenttotal <= total) {
if (check(i) > currenttotal) { //Finding if the
triangle = i;
if (currenttotal == total) break;
}
i++;
}
System.out.println("The value of the first triangle number to have over 500 divisors is " + triangle);
}
}
編輯:
與最終代碼固定爲
import java.util.ArrayList;
public class Level_12 {
/*
The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
*/
public static ArrayList<Long> check(long num) {
ArrayList<Long> divisors = new ArrayList<Long>();
for (long o = 1; o <= Math.sqrt(num); o++)
if (num % o == 0) {
divisors.add(o);
System.out.println(o + " is a current divisor of " + num);
}
return divisors;
}
public static void main(String[] args) {
long triangle = 0; //Triangle number
long total = 500; //Total divisors
long currenttotal = 0; //Amount of divisors
long i = 0; //Just to itterate
while (currenttotal <= total) {
if (check(i).size() > currenttotal) { //Finding if the amount of divisors is larger than current divisors
triangle = i;
if (currenttotal == total) break;
}
i++;
}
System.out.println("The value of the first triangle number to have over 500 divisors is " + triangle);
}
}
順便說一句,錯誤是在方法「檢查()」。 – duelingwarlord
'return m'不返回一個ArrayList,而是一個'Long'。那就是問題所在。可能你只是想返回「除數」。 – qqilihq
你不能從一個方法中返回多個值(就像你試圖做的那樣,用return語句看你的循環)。而是返回ArrayList。 –