Recursion problem – is this solution correct, and is there a simpler one?

Tags: ,



I am new to recursion and I found the following Java problem:
Write a function that gets an integer n, and prints the numbers 1!,2!,3!,…,n!.
Here is what I did and I would like to know if this is the simplest solution (I am not sure because I used “for” loop to do it).

public static void Print(int n) {
  if (n == 0) {
    System.out.print("1");
  } else {
    int temp = 1;
    for (int i = 1; i <= n, i++) {
      temp = temp * i;
    }
    Print(n-1);
    System.out.print(temp);
  }
}

By the way, the previous exercise was to write a function that gets an integer n and returns n!, using recursion. Do you think I need to use it here and print it instead of calculating temp (n!) and print it? Thanks!

Answer

Here is a simple recursive solution:

  public static long factorial(long n) {
    if(n == 0 || n == 1) {
      System.out.print(1 + " ");
      return 1;
    }

    long result = n * factorial(n - 1);
    System.out.print(result + " ");
    return result;
  }


Source: stackoverflow