通过键盘输入n时从1到n打印质数

时间:2019-07-02 14:45:24

标签: c

我知道我的代码有点奇怪,但是我才开始编码 有人可以帮我弄清楚为什么我的代码不起作用

    int n,i,j;
    printf("enter the value\n");
    scanf("%d",&n);
    for(i=2;i<=n;i++)
    {
       for(j=2;j<=i;j++)
        {
            if( (i%j==0) && (i!=j)  )
            {
                 break;
            }
            else if(i!=j)
            {
                 continue;
            }
        }
        if(i==j)
        {
              printf("prime no are %d\n",i);
               continue;
        }
   }

2 个答案:

答案 0 :(得分:1)

当数字为素数时,程序不记录。试试:

    int n,i,j,prime_count;
    bool is_prime;

    printf("enter the value\n");
    scanf("%d",&n);

    prime_count = 0;

    for(i=2;i<=n;i++)
    {
       is_prime = true;

       for(j=2;j<i;j++)
        {
            if( (i%j) == 0 )
              {
                 is_prime = false;
                 break;
              }

            // As said by Achal you may not need this condition, 
            // Your loop will continue by itself
            // else if(i!=j)
            //  {
            //     continue;
            //  }
        }
        if(is_prime)
           {
              prime_count++;
            }
   }

   // Then you can do what you want with the number of primes found
   // e.g. print it :
   printf("Number of primes: %d\n", prime_count);

答案 1 :(得分:0)

您的for循环已关闭1。应该是:

for(j=2;j<i;j++)

如果数字为质数,则当前j将为i + 1,因此您的最终检查失败