打印最高为n的素数

时间:2015-09-24 19:39:40

标签: c numbers

我已经编写了一些代码来询问用户n,然后将素数打印到n。但是当我使用它时,即10,它只打印非素数

 /* Asks for the amount of prime numbers you would like to print, then prints them */

#include <stdio.h>

int main(void)
{
    int n, i, j, check;
    printf("How many prime numbers would you like to print? ");
    scanf("%d", &n);

    for (i = 2; i <= n; i++) {
        check = 0;

        for (j = 2; j < i ; j++) { 
            if (i % j == 0) {
                check = 1;              
                if (check == 1) {
                    printf("%d\n", i);
                }
            }
        }
    }       

    return 0;
}

How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10

我已经尝试了一切,但我想我错过了一些非常微不足道的事情!

4 个答案:

答案 0 :(得分:2)

应该是这样的:

for (i = 2; i <= n; i++)
{
    check = 0;

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

        if (i % j == 0)
        {
            check = 1;
            break;
        }
    }
    if (check == 0)
    {
        printf("%d\n", i);
    }
}

此外,在内循环中,您不必将数字除以j < i。你不必超越i/2

答案 1 :(得分:1)

正如Weather Vane所说,如果%可以被i完全整除,则mod运算符j会返回0,如果这是真的,则数字主要。你的条件陈述是倒退的。

#include <stdio.h>
int main(void)
{
   int n, i, j, check;
   printf("How many prime numbers would you like to print? ");
   scanf("%d", &n);

   for (i = 2; i <= n; i++) 
   {
       check = 0;
       for (j = 2; j < i ; j++) 
       { 
           if (i % j == 0) 
           {
               check = 1;
               break;
           }
       }
       if (check == 0)
       {
           printf("%d\n", i);
       }
   }

   return 0;
}

How many prime numbers would you like to print? 10
2
3
5
7

答案 2 :(得分:1)

有几个问题。

首先,当您设置check = 1时,这意味着i均匀划分,因此n 不是素数,所以您不应该打印它。您应该在check == 0时打印该号码。

其次,您每次都要通过内循环进行打印。您应该在循环结束时测试check,以确保没有数字将其分开。

作为改进,一旦找到一个均匀划分的数字,就不需要继续检查。因此,只要设置check = 1,就可以突破内循环。

#include <stdio.h>

int main(void)
{
    int n, i, j, check;
    printf("How many prime numbers would you like to print? ");
    scanf("%d", &n);

    for (i = 2; i <= n; i++) {
        check = 0;

        for (j = 2; j < i ; j++) { 
            if (i % j == 0) {
                check = 1;
                break;
            }
        }
        if (check == 0) {
            printf("%d\n", i);
        }
    }       

    return 0;
}

答案 3 :(得分:0)

尝试查看此代码

#include <stdio.h>

int IsPrime(int num)
{
    int i = 2;

    for (i = 2; i < num; i++) if (num % i == 0) return 0;

    return 1;
}

int main(void)

{
    int n, i;
    char *nStr = (char*)malloc(10);

    printf("How many prime numbers would you like to print? ");
    fgets(nStr, 9, stdin);
    n = atoi(nStr);

    for (i = 1; i <= n; i++) if (IsPrime(i)) printf("%d\n", i);

    getchar();
    return 0;
}

关于您的代码,只有在支票保持为0时才应打印该号码。