【问题标题】:Finding the largest factorial that is less than the number entered查找小于输入数字的最大阶乘
【发布时间】:2020-11-01 17:32:35
【问题描述】:
基本上我希望我的代码做的是将阶乘结果与输入的数字进行比较,以找到小于输入数字的最大阶乘。由于某种原因,它没有打印任何内容。
public class Main {
public static void main(String[] args) {
int numinput = 150; //number than we are trying to find the largest factorial less than
int num = 1; //number than we are solving a factorial for, to test against numinput
int factorial = 1; //actual result of the factorial
while (factorial < numinput) //finds the factorial of num
for(int i = 1; i <= num; i++) {
factorial *= i;
}
num++;
if (factorial > numinput) {
num--;
System.out.println("The largest factorial less than " + numinput + "is !" + factorial);
}
}
}
【问题讨论】:
标签:
java
numbers
factorial
【解决方案1】:
while 循环没有花括号,所以循环体中唯一的东西是for 循环。 num 从 1 开始,循环中的任何内容都不会增加它,所以它会永远循环。
不过,您不需要嵌套循环 - 一个计算阶乘的循环就足够了:
int numinput = 150; //number than we are trying to find the largest factorial less than
int num = 1;
int factorial = 1;
while (factorial < numinput) {
num++;
factorial *= num;
}
// We overshot to terminate the loop, go back one number
factorial /= num;
num--;
System.out.println
("The largest factorial less than " + numinput + " is " + num + "!, or " + factorial);
【解决方案2】:
那是因为你的代码无法跳出这个while循环-
while (factorial < numinput) //finds the factorial of num
for(int i = 1; i <= num; i++) {
factorial *= i;
}
由于您没有在 while 循环中使用括号,因此它刚刚获得了 for 循环,并且由于 num 的值永远不会增加,它会一直将 factorial 永远乘以 1。我想你想这样做 -
public class Main {
public static void main(String[] args) {
int numinput = 150; //number than we are trying to find the largest factorial less than
int num = 1; //number than we are solivng a factorial for, to test agaisnt numinput
int factorial = 1; //actual result of the factorial
while (factorial < numinput) {
for(int i = 1; i <= num; i++) {
factorial *= i;
}
num++;
if (factorial > numinput) {
num--;
System.out.println("The largest factorial less than " + numinput + "is !" + factorial);
}
}
}
}
但是我检查了你的代码输出为 150,它是不正确的。我在下面提供我的代码 -
public class Main {
public static void main(String[] args) {
int numinput = 150; //number than we are trying to find the largest factorial less than
int num = 1; //number than we are solivng a factorial for, to test agaisnt numinput
int factorial = 1; //actual result of the factorial
while (factorial <= numinput) { // continue multiplying even if equal
factorial = 1;
for(int i = 1; i <= num; i++) {
factorial *= i;
}
num++;
}
// now the factorial is surely greater than numinput, and it is the factorial of
// current value of num - 1, we can remove the conditional
// and reduce the factorial by num -1 since multiplying by num - 1 has
// made it bigger than numinput
factorial /= (num - 1);
System.out.println("The largest factorial less than " + numinput + "is !" + factorial);
}
}
【解决方案3】:
我假设您说的是小于输入阶乘的最小整数阶乘。所以,代码应该是这样的:
public static void main(String[] args) {
int input = 150; // example
for (int i = 1; i <= input - 1; i++) {
int sum = (input - 1) * 1;
}
System.out.println(input);
}