我知道我可以使用一个额外的变量计算dvisors但我的问题是为什么这条线不行? prime = num / 1 == num&& num / num == 1; 另请查看以下有问题代码中的注释。感谢。
#include <stdio.h>
int main()
{
long num = 0;
long req = 0;
int control = 0;
int div = 1;
int prime;
printf("Give starting number: ");
scanf("%d", &num );
printf("\nGive required numbers: ");
fflush(stdin);
scanf("%d", &req);;
while(req > control)
{
printf("\nNumber is: %d ", num);
prime = num / 1 == num && num / num == 1; /*This lines here why dosnt thi work?*/
if(prime) /*Also here lets say the above line work with what do i avaluate the if with so it only prints tha asterisk for the prime numbers?*/
printf("* ");
printf("Equal Divisors are: ");
while(div <= num)
{
if(num % div ==0)
printf("%d ", div);
div++;
}
if(req == control)
break;
num++;
control++;
div=1;
printf("\n");
}
return 0;
}
答案 0 :(得分:1)
Primes是仅由它们自己和1均分的数字。所以你必须遍历所有其他除数,最多为num / 2,并确保它们不给出整数结果。 (从技术上讲,你只需循环遍历所有PRIME数字除数 - 2,3,5,7,11等 - 但这样做更难。)
编辑:正如@thb在评论中指出的那样,你必须遍历所有其他除数,最多为sqrt(num),而不是num / 2.
这是一些伪代码:
Set a Boolean variable to "True" (meaning "yes, it's a prime").
Loop from 2 to sqrt(num).
If num divided by the loop counter is an integer, then...
It's NOT a prime number.
Set the Boolean variable to "False".
If you can exit the loop there, great. But no big deal if you can't.
After the loop, if the Boolean variable = "True" then it's a prime number. If it's "False" then it's not a prime number.
答案 1 :(得分:0)
一个问题是表达式的排序。这条线
prime = num / 1 == num && num / num == 1;
相当于
{
const bool a = ((num / 1) == num);
const bool b = ((num / num) == 1);
prime = a && b;
}
这是一个容易犯的错误。无论如何,有人怀疑prime = a && b;
是你的意思。