我写了这个算法来检查一个数字是否为素数以及哪个数字除以它。现在我想知道什么是600851475143除数(例如),它输出一个负数。 那是我的代码:
#include <stdio.h>
/* Discover what numbers divide the one read as input, then show if it's prime */
int main() {
long checker;
long step = 1;
int divisors = 0;
printf("Enter with the number you want know the divisors: ");
scanf("%ld", &checker);
while(step <= checker){
/* check which numbers divide the number read*/
if (checker % step == 0) {
printf("%ld divides %ld\n", step, checker);
step +=1;
divisors +=1;
}
else{
step+=1;
}
}
/*Now check if it is prime*/
if (divisors == 2) {
printf("ADDITIONAL INFO: %ld IS a prime number.\n", checker);
}
else {
printf("ADDITIONAL INFO: %ld IS NOT a prime number.\n", checker);
}
printf("Done!\n");
return 0;
}
答案 0 :(得分:2)
问题是,您使用格式字符串scanf
long
到%d
,该格式字符串需要int
变量的地址。您使用printf
的方式也是如此。
您需要在格式字符串中将%d
替换为%ld
。
您基本上需要这样做,因为int
和long
的大小不相等。
编辑:GCC使用-Wall
选项指出错误。