Prime number program in C

旧街凉风 提交于 2019-12-11 20:18:27

问题


This program is supposed to print the first x prime numbers, but I noticed that it was printing some non-prime numbers, such as 27 or 35. I've been looking at it for hours and nothing seems to pop up. So please, if you know what's wrong, tell me.

#include <stdio.h>
int main(){
    int i=0, cont=2, prim=2, quant;
    printf("Insert number of prime numbers you wish: ");
    scanf("%d", &quant);
    printf("The first %d prime numbers are:\n", quant);
    while(i<quant){
        if(prim%cont!=0 && (cont>1 && cont<prim)){
            cont++;
        }
        else if(prim%cont==0 && (cont>1 && cont<prim)){
            prim++;
        }
        else if(prim%cont==0 && cont==prim){
            printf("%d\n", prim);
            prim++;
            cont=2;
            i++;
        }
    }
    return 0;
}

回答1:


Code:

int count = 0, quant = 5, i, j;

int flag = 0;
for(prim = 2 ; count <= quant ; prim ++) {
    flag = 0;
    for(j = 2; j < prim/2; j++) {
        if(prim % j == 0) {
            flag = 1;
            break;
        }
    }
    if(flag == 0) {
        printf("%d\n", prim);
        count++;
    } 
}

Update your code as:

while(i<quant){
    if(cont<prim) {
        if(prim%cont!=0) {
            cont++;
        } else {
            prim++;
            cont = 2; // restart cont
        }
    }
    else if(prim%cont==0 && cont==prim){
        printf("%d\n", prim);
        prim++;
        cont=2;
        i++;
    }
}



回答2:


Try this

#include<stdio.h>

int prime(int n)
{
    int i, j, len=1, brk=0;
    int list[200]={2};
    for(i=2; i<=n; i++)
    {
        for(j=0; j<len; j++)
        {
            if(i%list[j]==0){
                brk=1;
                break;
            }
            else
            {
                brk=0;
            }
        }
        if(brk==0)
        {
            list[len]=i;
            len++;
        }
    }
    for(i=0; i<len; i++)
        printf("%d ",list[i]);
}

main()
{
    int i, n;
    scanf("%d",&n);
    prime(n);
}



回答3:


Simple way is to find is: if a number is not divisible by 2,3 & 5, its a prime number.

#include <stdio.h>

int main()
{

    int num = 35;
    int i = 5;
    printf("1 2 3 5");
    while (i <= num)
    {
        if ((i % 2) && (i % 3) && (i % 5))
        {
                printf(" %d",i);

        }
        i++;
    }
    printf("\n");
    return 0;
}


来源:https://stackoverflow.com/questions/26667217/prime-number-program-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!