显示获取数字阶乘的整个计算 (java)

Display whole calculation for getting a factorial of a number (java)

我有一个简单的 java 程序计算一个数的阶乘。

我在 运行 程序后得到的输出:

the factorial of 5 is 120

但是我想生成如下所示的输出:

5 * 4 * 3 * 2 * 1 = 120

public static int calculateFactorial(int numInput) {
    
    int factorial = 1;
    
    for (int i = 1; i <= numInput; i++) {
    factorial = factorial *i;
    }
    
    return factorial;
}
public static String calculateFactorialStr(int val) {
    String res = IntStream.range(0, val)
                          .map(i -> val - i)
                          .mapToObj(String::valueOf)
                          .collect(Collectors.joining(" * "));
    return res + " = " + calculateFactorial(val);
}

public static long calculateFactorial(int val) {
    long res = 1;

    for (int i = 2; i <= val; i++)
        res *= i;

    return res;
}
public static String calculateFactorial(int numInput) {
    int factorial = 1;
    String calc = "";

    for (int i = 1; i <= numInput; i++) {
      if (i != 1) {
        calc += " * ";
      }
    calc += i;
    factorial = factorial * i;
    }
    calc += " = " + factorial;
    return calc;
}

或者,如果您更喜欢 x * (x-1) * ... * 1

  public static String calculateFactorial(int numInput) {
    
    int factorial = 1;
    String calc = "";

    for (int i = numInput; i > 0; i--) {
      if (i != numInput) {
        calc += " * ";
      }
    calc += i;
    factorial = factorial * i;
    }
    calc += " = " + factorial;
    return calc;
}

静态方式: 在你的函数中创建你的字符串(这 not 操作 n < 0):

public static String calculateFactorial(int numInput) {
        StringBuilder res = new StringBuilder();
        int factorial = 1;

        for (int i = 1; i <= numInput; i++) {

            res.append(String.valueOf(i));
            if (i != numInput) {
                res.append(" * ");
            }
            factorial = factorial *i;
        }
        res.append(" = ").append(factorial);

        return res.toString();
}

面向对象的方式: 如果您了解 Java 中的面向对象,您还可以创建阶乘 class(这 在 n < 0 的情况下运行):

import java.util.ArrayList;
import java.util.List;

public class Factorial {
    private int number;
    private int result;

    public Factorial(int numInput) {
        number = numInput;
        int factorial = 1;

        for (int i = 1; i <= numInput; i++) {
            factorial = factorial * i;
        }
        result = factorial;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i <= number; i++) {

            res.append(i);
            if (i != number) {
                res.append(" * ");
            }
        }
        res.append(" = " + result);

        return res.toString();
    }
}


然后你可以使用System.out.println(new Factorial(n));打印结果