I'm trying to compute the combination
procedure(factorial(n)/(factorial(r)*factorial(n-r))
.
When I call the factorial
method from within the combination
method, when running I get a stackoverflow error
before the calculation.
The instructions read "This method should receive two integers as its parameters, n and r. Your combination method should call the factorial method inside its definition by using it in the following formula:"
Any help will be appreciated we haven't really covered stackoverflow so I'm a little lost. Thank you!!
import java.util.Scanner;
public class lab6_Perea{
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
System.out.println("Hello! Welcome to Set calculator. Please select the calculation you want to perform \n\t1. Power \n\t2. Factorial \n\t3. Combination \n\t4. Permutation");
int option = sc.nextInt();
switch(option){
case 1:
System.out.println("Please enter the base and exponent: ");
int x = sc.nextInt();
int y = sc.nextInt();
System.out.print("The answer is: " + power(x, y));
break;
case 2:
System.out.println("Please enter a number: ");
int z = sc.nextInt();
System.out.print("The facotrial of " + z + " is " + factorial(z));
break;
case 3:
System.out.println("Please enter 2 numbers to calculate the Combination: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.print("The total combination is: " + combination(a, b));
break;
case 4:
// FIX ME call Combination method
break;
}
}
public static int power(int n, int m){
if(m==0)
return 1;
else
return (n * power(n, m-1));
}
public static int factorial(int n){
if(n == 0)
return 0;
else
return (n * factorial(n-1));
}
public static int combination ( int n, int r){
int combo =factorial(n)/(factorial(r)*factorial(n-r));
return combo;
}
}