简体   繁体   中英

I've got infinite looping

i am practicing my java by counting possible ways to reach n with a dice. and when input n value to smaller number, it works. but when i input n value to 100, it got infinite looping.

can u guys help me ?

here is my code :

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);
        }
    }

Your problem is similar to Fibonnaci's one :

x0 = 0, x1 = 1, x(N) = x(N-2) + x(N-1)

If you need to do it with big numbers you should use a non-recursive method :

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;
    } 

At each iteration you just calculate the sum of the precedent ones

I've tested with n = 32 => with yours it took 8sec, with this one it took less than 1sec (I tried with n = 1000 => always 1sec, but i didn't try yours haha, after n = 35 it's a bit long ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM