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?
From the initial values, nk = -10. Since this is less than 0, your factorial method will never return
(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.
c= factorial(n)/(factorial(k)*factorial(nk));
For n=5 and k=15,
factorial(nk) 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.
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.