我想回答项目欧拉问题编号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'。 –