stress_Ballz stress_Ballz - 7 months ago 14
Java Question

Using recursion to compute factorials without new variables

I am trying to compute the entered factorial in the method factorialRecursive by using recursion, However I cannot declare any variables or objects in that method and thats what i am struggling with, my attempt is in the method already but doesn't work.

class Factorial{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = input.nextInt();
} while (number < 0);
System.out.println(number + "! = " + factorialIterative(number) + " (iterative)");
System.out.println(number + "! = " + factorialRecursive(number) + " (recursive)");
}

private static int factorialIterative(int num) {
int result = 1;
while (num > 0) {
result = num*result;
num--;
}
return result;
}

private static int factorialRecursive(int num){
if (num==1 | num==0)
return 1;
return num*(num-1) * num;
}
}

Answer

Try this:

private static int factorialRecursive(int num) {
    // Warning here use || instead of |
    if (num==1 || num==0)
        return 1;
    return num * factorialRecursive(num - 1);
}

I can also be simplified like this:

private static int factorialRecursive(int num) {
    return (num == 1 || num == 0) ? 1 : num * factorialRecursive(num - 1);
}
Comments