我正在通过计算用骰子达到n的可能方法来练习我的java。 当输入n值较小的数字时,它起作用。 但是当我输入 n 值为 100 时,它会无限循环。
你们能帮我吗?
这是我的代码:
public static void main(String[] args)
{
testCode test = new testCode();
System.out.println(test.countWays(100));
}
private static int countWays(int n)
{
if(n<=1)
{
return 1;
}
else
{
System.out.println("counting ....");
return countWays(n-6) + countWays(n-5) + countWays(n-4) + countWays(n-3) + countWays(n-2) + countWays(n-1);
}
}
最佳答案
您的问题与斐波那契的问题类似:
x0 = 0, x1 = 1, x(N) = x(N-2) + x(N-1)
如果您需要处理大数字,您应该使用非递归方法:
static long countBis(int n) {
long fn, f1, f2, f3, f4, f5, f6;
int i;
f1=f2=f3=f4=f5=f6=fn = 1;
for ( i = 2; i <= n; i++ ) {
f6 = f5;
f5 = f4;
f4 = f3;
f3 = f2;
f2 = f1;
f1 = fn;
fn = f6 + f5 + f4 + f3 + f2 + f1;
}
return fn;
}
在每次迭代中,您只需计算先前迭代的总和
我用 n = 32
=> 测试了你的,花了 8 秒,用这个花了不到 1 秒(我尝试用 n = 1000
=>总是1秒,但我没有尝试你的哈哈,在n = 35
之后有点长^^
关于java - 我有无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053627/