查找小于输入数字的最大阶乘



本质上,我希望我的代码所做的是将阶乘结果与输入的数字进行比较,以找到小于输入数字的最大阶乘。出于某种原因,它没有打印任何内容。

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);
}
}
}

while循环没有大括号,所以循环体中唯一的东西就是for循环。num1开始,循环中没有任何东西会增加它,所以它将永远循环。

不过,您不需要嵌套的循环——一个在执行过程中计算阶乘的单个循环就足够了:

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);

这是因为您的代码在循环-时无法摆脱这个问题

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);
}
}

我假设你说的是小于输入阶乘的最小整数阶乘。所以,代码应该是这样的:


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);
}

最新更新