Code to calculate the first N prime numbers in C?

4

First, I have this here:

#include <stdio.h>
#include <stdlib.h>

int main(){

   int i=13,w=0,k;

   for(k=i-1;k!=1;k--){

      if(i%k==0){w=1; break;}        
   }               

   if(w==0){ printf("\n%d eh primo",i); }

   system("pause");    
   return 0;    
}

In this particular case, calculate whether 13 is prime or not. Now, I want to make one to display the first "n" first cousins, I did this, but it does not work as I expected:

#include <stdio.h>
#include <stdlib.h>

int main(){

   int i=2,w=0,k,j=1;

   while(1==1){    

      for(k=i-1;k!=1;k--){

         if(i%k==0){w=1; break;}          
      }       

      if(w==0){ j++; printf("\n%d eh primo",i); }

      if(j==7) break;

      i++;             
   }

   system("pause");    
   return 0;    
}

This would be to display the first 7 cousins, but only displays 2 and 3. Why this? I created an integer j to be incremented whenever prime occurs. When he turns 7 the loop to.

I am grateful to anyone who helps me. Thank you for your attention.

    
asked by anonymous 24.12.2015 / 17:24

2 answers

4

This error is happening because when w receives 1 it does not return to the initial value that is 0. Try this way.

for(k = i - 1, w = 0; k != 1; k++)
{
     if(i%k==0)
     {
         w = 1;
         break;
     }
}

so when you return to loop the value of w will be 0 again.

    
24.12.2015 / 22:04
0

Code to perform a prime search within a user-defined range.

#include <stdio.h>
main() {
int a,b,f,i,r,min,max,z;
printf("Digite dois valores para ser calculado os numeros primos dentro do intervalo:\n");
scanf("%d %d",&a,&b);
if (a<b){
    min=a; max=b;
    }
else {
    min=b; max=a;
    }
i=2; z=0; f=0;
printf("\nValores entre %d e %d:\n",min,max);
while(min<=max) {
    while(min>=i) {
        r=min%i;
    if (r==0)
        z=z+1; i=i+1;
    }
    if (z==1){
        f=f+1;  if (f==1)
                    printf("(%d",min);
            else if (f>1)
                    printf(", %d",min);
    }
    min=min+1; i=2; z=0;
    }
if (f>0)
    printf(")\n\n");
else
    printf("Sem valores nesse intervalo.\n\n");
getchar();
}

This code is executed even if the first number entered is greater than or equal to the second number.

    
02.02.2016 / 09:09