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
(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 to share