Code for calculating the first N primes in C?

Asked

Viewed 6,127 times

4

First, I got this:

#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, it calculates whether 13 is prime or not. Now, I want to do one to display the first "n" cousins, I did it, but it doesn’t 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 7 first cousins, but only displays 2 and 3. Why is that? I created an integer j to be incremented whenever cousin happens. When he turns 7 the loop to.

I am grateful to those who help me. Thank you for your attention.

  • 4

    Which one do you think is best suited to answer that? http://answall.com/q/84040/101, http://answall.com/q/85565/101, http://answall.com/q/85562/101, has others.

  • 1

    I don’t think his question is a duplicate of any of the ones you suggested, @bigown. His case is different.

2 answers

5

this error is happening because when w gets 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 the loop the value of w will be 0 again.

  • It worked. That’s right. VLW!

  • There’s a way I can make you feel better?

0

Code to perform a primes search in a user-determined 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 typed is greater than or equal to the second number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.