我试图在不使用标志变量的情况下找到一个数字的素数,但我不知道代码中有什么错误。
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num, i, j;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
printf("%d", i);
}
}
}
}
return 0;
}
您必须打印num
因子和素数的值。
在您的代码中,您正在打印num
的因子,但不是在看到存在除以i
的j
之后通过打印i
来素数。
相反,您应该检查j
的所有候选者,并在看到所有测试的j
不划分i
后打印i
。
此外,您可能需要在要打印的因子之间添加一些分隔符。
试试这个:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num, i, j;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
break; /* stop iteration because a factor is found */
}
}
if (j > i / 2) /* check if the iteration ended not by finding factor but by checking all candidates */
{
printf("%dn", i);
}
}
}
return 0;
}
您的方法感觉有点复杂。也许只是做一些类似的事情:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
unsigned num = argc > 1 ? strtoul(argv[1], NULL, 10) : 137;
int count = 0;
printf("%d = ", num);
for( unsigned i = 2; i <= num; i++ ){
while( num % i == 0 ){
printf("%s %d", count++ ? " *" : "", i);
num /= i;
}
}
printf(" ( %d factor%s )n", count, count == 1 ? "" : "s");
return 0;
}