3

I've try to use long and double with c, k, n variables but netbeans shows me a stack overflow 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

Do I have to use integer literals or long.parselong

What I am doing wrong?

Rudy Matela
  • 6,310
  • 2
  • 32
  • 37
ger
  • 414
  • 1
  • 4
  • 22

3 Answers3

19

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

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • should I use Math.abs(n-k) ??? [link]http://stackoverflow.com/questions/493494/make-a-negative-number-positive-in-java[link] – ger Apr 16 '15 at 19:29
  • 1
    @ger I would recommend that if k is larger than n you should throw an Exception – ControlAltDel Apr 16 '15 at 19:58
3

(number == 0) may not happen due to binary representation of number. Even with some tolerance level added, it is still incomplete this way. You may need negative number conformance. (10-10 maybe not zero)

Each time it goes deeper in function stack because of recursivity, it consumes more memory for function variables and parameters until java cannot plea more from operating system.

huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97
  • 1
    Sorta, but no. Floating-point arithmetic doesn't just randomly lose precision. Addition and subtraction of `double` values representing small integers is exact, for a value of "small" that easily accommodates the values that would appear in the intended binomial coefficient computation. – John Bollinger Apr 16 '15 at 18:54
2

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

For n=5 and k=15,

factorial(n-k) would become: factorial(-10)

and then..

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

and like this it would

continue indefinitely never reaching 0.

hence the stack will overflow.

Santanu
  • 893
  • 3
  • 10
  • 24