【发布时间】:2021-09-09 14:21:56
【问题描述】:
您好,我是 C 新手,我选择了一个项目来变得更好
如果根据 Collatz 猜想,我想制作一个程序来暴力破解每个数字。
科拉茨猜想:
对于那些不知道 Collatz 猜想是什么的人,请点击 here
总结:
如果一个数是奇数,则乘以 3 并增加 1
如果它被2除
重复此操作,直到达到 1
我的代码:
#include <stdio.h>
int main(){
int n, x, a, b;
n = 5; //number we check first (has to be bigger than 4 because 4,3,2,1 is a loop)
//n is later on a number that is currently being tested
//all numbers smaller than 2 ** 64 were brute force tested and are according to Collatz's conjecture
x = n; //x begins as n and then changes according to rules of cenjecture until it reaches 1
a = 1; //a is set to 1 until x = 1 which means that number n is according to conjecture
b = 1; //creates an infinite loop
while(b == 1){ //runs forever
if(a == 1){
if(x == 1){
a = 0; //if x reaches 1 (number n is according to conjecture) a is set to 0 and n is increased by 1 ===
} // ||
else{ // ||
if(x % 2 == 0){ // ||
x = x / 2; // ||
} // ||
else{ // ||
x = x * 3 + 1; // ||
} // ||
} // ||
} // ||
else{ // ||
printf("%d \n", n); // ||
n = n + 1; // <<<<<============================================================================
x = n; //
a = 1; //
}
}
}
问题:
问题是,当我运行它时,它会在编号 113383 处停止并且出现问题。我什至让它运行了 5 分钟以上,但它什么也没做。我什至尝试在我的 python 程序中运行相同的数字来测试输入数字,并且它很快就有了。 我尝试从 n = 113384 开始,它工作并在 134378 再次停止。
数字 113383 在 C 中是否有所不同,或者我的代码中是否存在缺陷。
如果可以,请提供帮助。
非常感谢
【问题讨论】:
-
如果你想要一个无限循环,你可以写
while (1),你不需要额外的变量b。