Why is this code sending me Stackoverflow in java

I'm trying to use long

, and double

with variable c, k, n

, but netbeans shows me the error:

public class Main {

public static void main(String[] args) {
   double c=0; //combinatorial
   double n=5;
   double k=15;

   c= factorial(n)/(factorial(k)*factorial(n-k));

   System.out.print(n+" combinatorial "+k+" between "+c+"\n");

}

    static double factorial (double number) {
        if (number == 0) 
            return 1;
          else 
            return number * factorial(number-1);
   }
}

Exception in thread "main" java.lang.StackOverflowError
    at co.combinatorial.Main.factorial(Main.java:26)
    at co.combinatorial.Main.factorial(Main.java:29)
    at co.combinatorial.Main.factorial(Main.java:29)
    at co.combinatorial.Main.factorial(Main.java:29)
......

      

Java Result: 1

Should I use integer literals or long.parselong

What am I doing wrong?

+3


source to share


3 answers


From the initial values, nk = -10. Since it is less than 0, your factorial method will never return.



+19


source


(number == 0) may not happen due to the binary representation of the number. Even with some clearance level added, it is still incomplete. You may need a negative numeric match. (10-10, maybe not zero)



Every time it gets deeper in the function stack due to recursiveness, it consumes more memory for function variables and parameters until java can no longer be away from the operating system.

+3


source


c = factorial (n) / (factorial (k) * factorial (nk));

For n = 5 and k = 15,

factorial (nk) becomes: factorial (-10)

and then..

number * factorial (number-1) will give us: -10 * factorial (-11),

and how is that,

continue infinitely never reach 0.

so the stack will overflow.

+2


source







All Articles