卡在循环 Collatz 猜想 C 中的尝试
Stuck in Loop Collatz Conjecture Attempt in C
我的代码中存在逻辑缺陷,我似乎无法将 2^31 − 1 作为输入传递。这是我的代码片段。
#include <stdio.h>
int main() {
long input = 0;
long temp = 0;
int count = 0;
printf("Enter a positive integer ( or 0 to quit): ");
scanf("%ld", &input);
if(input == 0)
{
printf("Quit.");
}
else
{
temp = input;
while (temp != 1)
{
if(temp %2 ==0)
{
temp = temp/2;
count++;
} else
{
temp = 3*temp + 1;
count++;
}
}
return 0;
}
我已经尝试将输入的大小更改为 long => long long,但在调试后它仍然卡在这个区域内。请提供一些反馈谢谢!
假设您的系统有一个 long 64 位,然后将其更改为与 unsigned long
一起使用,包括 scanf()
,似乎工作正常:
#include <stdio.h>
#include <assert.h>
int main() {
unsigned long input;
assert(sizeof(input) * 8 >= 64);
while (1) {
printf("Enter a positive integer (or 0 to quit): ");
(void) scanf("%lu", &input);
if (input == 0) {
break;
}
unsigned int count = 0;
while (input != 1) {
if (input % 2 == 0) {
input /= 2;
} else {
input = 3 * input + 1;
}
count++;
}
printf("%d\n", count);
}
printf("Quit.\n");
return 0;
}
用法
> ./a.out
Enter a positive integer (or 0 to quit): 2147483647
450
Enter a positive integer (or 0 to quit): 0
Quit.
>
要不然,找点其他的64位类型(long long?)来用。 Python 有效,因为它有无限大的整数。
A long int
不一定要超过 32 位。为确保您使用的是 64 位整数,最好使用 inttypes.h
中的 int64_t
类型,并在调用中使用 PRId64
宏而不是 ld
scanf()
.
不过,在任何普通的桌面系统上,您至少应该在此处获得一个 32 位 int。但是,问题出在这行代码中:
temp = 3 * temp + 1;
如果输入是 2^31-1,那么这将溢出一个 32 位整数。
我的代码中存在逻辑缺陷,我似乎无法将 2^31 − 1 作为输入传递。这是我的代码片段。
#include <stdio.h>
int main() {
long input = 0;
long temp = 0;
int count = 0;
printf("Enter a positive integer ( or 0 to quit): ");
scanf("%ld", &input);
if(input == 0)
{
printf("Quit.");
}
else
{
temp = input;
while (temp != 1)
{
if(temp %2 ==0)
{
temp = temp/2;
count++;
} else
{
temp = 3*temp + 1;
count++;
}
}
return 0;
}
我已经尝试将输入的大小更改为 long => long long,但在调试后它仍然卡在这个区域内。请提供一些反馈谢谢!
假设您的系统有一个 long 64 位,然后将其更改为与 unsigned long
一起使用,包括 scanf()
,似乎工作正常:
#include <stdio.h>
#include <assert.h>
int main() {
unsigned long input;
assert(sizeof(input) * 8 >= 64);
while (1) {
printf("Enter a positive integer (or 0 to quit): ");
(void) scanf("%lu", &input);
if (input == 0) {
break;
}
unsigned int count = 0;
while (input != 1) {
if (input % 2 == 0) {
input /= 2;
} else {
input = 3 * input + 1;
}
count++;
}
printf("%d\n", count);
}
printf("Quit.\n");
return 0;
}
用法
> ./a.out
Enter a positive integer (or 0 to quit): 2147483647
450
Enter a positive integer (or 0 to quit): 0
Quit.
>
要不然,找点其他的64位类型(long long?)来用。 Python 有效,因为它有无限大的整数。
A long int
不一定要超过 32 位。为确保您使用的是 64 位整数,最好使用 inttypes.h
中的 int64_t
类型,并在调用中使用 PRId64
宏而不是 ld
scanf()
.
不过,在任何普通的桌面系统上,您至少应该在此处获得一个 32 位 int。但是,问题出在这行代码中:
temp = 3 * temp + 1;
如果输入是 2^31-1,那么这将溢出一个 32 位整数。