哥德巴赫猜想是指任意大于 2 的偶数可以表示为两个质数之和。以下是使用 Java 编写的 Collatz 猜想验证程序:
public class CollatzConjecture {
public static void main(String[] args) {
int number = 27; // 你可以选择任意正整数作为起始值
System.out.println("Collatz 序列(起始值为 " + number + "):");
while (number != 1) {
System.out.print(number + " -> ");
number = collatz(number);
}
System.out.println("1");
}
private static int collatz(int n) {
if (n % 2 == 0) {
return n / 2;
} else {
return 3 * n + 1;
}
}
}
这个程序会根据 Collatz 猜想输出对应的序列。
你可以将 number 变量设置为任意正整数,然后查看对应的 Collatz 序列。
isdkz 发表于 2023-3-16 20:07
你描述的猜想实际上是“Collatz 猜想”(Collatz Conjecture),而不是“哥德巴赫猜想”(Goldbach Conject ...
collatz 这个是啥意思?
我是一个小白,不知道,希望求解 怎么把开头设为自己手动输入数字呢?
大大 岁月如此这般 发表于 2023-3-16 20:29
collatz 这个是啥意思?
我是一个小白,不知道,希望求解
collatz就是一个猜想的名字而已,你描述的那个不是 哥德巴赫猜想 ,而是 Collatz 猜想 isdkz 发表于 2023-3-16 20:32
collatz就是一个猜想的名字而已,你描述的那个不是 哥德巴赫猜想 ,而是 Collatz 猜想
手动输入数字进行验证应该用什么代码?大大
岁月如此这般 发表于 2023-3-16 20:34
手动输入数字进行验证应该用什么代码?大大
你可以使用 Scanner 类从命令行读取用户输入。下面是修改后的 Java 程序,允许用户输入一个正整数作为起始值:
import java.util.Scanner;
public class CollatzConjecture {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个正整数作为 Collatz 序列的起始值:");
int number = scanner.nextInt();
System.out.println("Collatz 序列(起始值为 " + number + "):");
while (number != 1) {
System.out.print(number + " -> ");
number = collatz(number);
}
System.out.println("1");
scanner.close();
}
private static int collatz(int n) {
if (n % 2 == 0) {
return n / 2;
} else {
return 3 * n + 1;
}
}
}
现在,程序会提示你输入一个正整数作为 Collatz 序列的起始值。
运行程序后,输入你选择的数字,然后程序将输出对应的 Collatz 序列。
页:
[1]