如何编写超级程序?

How do I write a superfactorial program?

Write a program to calculate and print the super factorial of a number using a for loop. The factorial of a number is the product of all integers up to and including that number, so the factorial of 4 (written as 4!) is 4*3*2*1= 24.

The super factorial is the product of all factorials up to and including that factorial.

4!!=4!*3!*2!*1!

我使用以下代码找到 "factorial":

import java.util.Scanner;
public class superfactorial {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner (System.in);

        // number whose factorial to be found
        int number;
        // prompting input
        System.out.print("Enter number: ");
            number = input.nextInt();

        int factorial = factorial(number);

        System.out.printf("the factorial of %d is %d", number , factorial);
    }

    // method that calculates the factorial
    public static int factorial (int n){
        int output = 1; 
        for (int i=1; i <= n; i++) {
            output = output * i;                
        }
            return output;
    }
}

考虑4个! = 4x​​3x2x1,可以看到分解中有4个数。一般n个分解会有n个数! (n(n-1)(n-2)....(n-(n-1))。因此,要获得超阶乘,您需要做的就是对分解中的每个分量进行阶乘。

伪代码看起来像这样

sp = 0 
for i = n to 1:
  sp = sp * factorial(i)
end for
return sp

你的阶乘方法中最重要的一行是这一行:

output = output * i;

您将 output 乘以 i,其中 i 是一个不断递增的整数。

超阶乘和普通阶乘有什么区别?要评估一个超阶乘,您不是将 output 乘以 i,而是乘以 i 的阶乘,对吗?

那就去做吧!我已经向你解释了整件事!只需创建一个名为 superfactorial 的新方法,复制阶乘方法中的所有内容并更改此行:

output = output * i;

对此:

output = output * factorial(i);

这是一个递归的方法。 基本上,在阶乘中乘以 n * fact(n-1)。在这里,我们做 fact(n) * superFact(n-1) 因为我们需要所有阶乘的乘积。

  int superfactorial(int n) {
    if (n == 0 || n == 1) {
      return factorial(n);
    } else {
      return factorial(n) * superfactorial(n-1);
    }
  }


  int factorial(int n) {
    if(n == 0 || n == 1) {
      return n;
    } else {
      return n * factorial(n-1);
    }
  }