我想回答項目歐拉問題編號53.我採取了一個相當暴力的方法,但在我看來,我的邏輯應該拿出正確的答案,即使它需要一段時間。在這種情況下,我做錯了什麼,除了效率相當低之外,那就是讓編譯器返回一個ArithmeticException除以零。ArithmeticException除以零
import java.util.*;
public class problem53
{
public static int fact(int x)
{
int total = 0;
if(x != 0)
{
for(int i=(x-1);i>0;i--)
{
x = x*i;
total = x;
}
}
if(x==0)
total = 1;
return total;
}
public static int combo(int y,int z)
{
int end = 0;
if(y==0)
y=2;
if(z==0)
z=1;
if(y-z != 0)
{
end = fact(y)/(fact(z)*(fact(y-z)));
}
return end;
}
public static void main(String[]args)
{
int answer = 0;
List<Integer> sure = new ArrayList<Integer>();
for(int i=20;i<=100;i++)
{
for(int j=2;j<i;j++)
{
int ferNow = combo(i,j);
if(ferNow>=1000000)
sure.add(ferNow);
}
}
answer = sure.size();
System.out.println(answer);
}
}
感謝您的幫助提前。
你'其實()'壞了。它會爲'fact(1)'返回'0'。 –