-1

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. This has to call itself in a While loop not a for loop.

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;
  }
}
  • **Factorial recursion** in **Java** has been handled many times on this site. A search for those three keywords brings up sufficient hits, one of which is in my closure vote. – Prune May 05 '16 at 16:46

3 Answers3

2

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);
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

You don't need to declare any variables. Take advantage of the recurrence relation for factorials:

n! = n * (n - 1)!

Multiply num by the result of making a recursive call by passing num - 1. Return that product without storing it in a variable.

rgettman
  • 176,041
  • 30
  • 275
  • 357
-1

Recursivity means you need to call the method itself inside of the method

Example:

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

and since factorial will increase really high with low values, consider to use other data type than integers... otherwise it will only work until factorial(16) after that you will get invalid data by using ints...

private static long factorialRecursive(long num){
         if (num==1 | num==0)
             return 1;
         return num*factorialRecursive(num-1);
      }
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97