不使用标志变量的数字的素数

  • 本文关键字:数字 变量 标志 c
  • 更新时间 :
  • 英文 :


我试图在不使用标志变量的情况下找到一个数字的素数,但我不知道代码中有什么错误。

#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的因子,但不是在看到存在除以ij之后通过打印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;
}