首页 > 解决方案 > 在通过键盘输入 n 时打印从 1 到 n 的素数

问题描述

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

    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;
        }
   }

标签: c

解决方案


该程序不记录数字何时为质数。尝试 :

    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);

推荐阅读