所以我已经为 Collatz 序列编写了代码,但我希望能够识别并打印出序列中出现的最大数字。这是我的代码:
import java.util.Scanner;
public class CollatzSequence {
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
int n,ts = 0;
System.out.print("This is the Lothar Collatz Sequnce. Please enter the starting number.\n>");
n = keyboard.nextInt();
do {
if (n % 2 == 0) {
n = n / 2;
System.out.println(n);
}
else {
n = n*3 + 1;
System.out.println(n);
}
ts++;
}
while (n != 1);
System.out.println("Terminated after "+ts+" steps.");
}
}
最佳答案
创建一个名为max
的变量。将其初始设置为等于n
。在每个步骤中,检查是否 n > max
,如果是,则将 max
设置为 n
。
关于java - 科拉兹序列 : Which number is the biggest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352388/