Search code examples
cprimes

specific number of integers


My requirement is to print x numbers of prime integer. So my code starts off by asking user to input a number, e.g. 7, I want it to produce 7 prime numbers.

I've now coded to a step where it produces all the prime numbers that are less than 50. But how do I code it in a way that I only want it to output, in this case, 7 prime numbers ?

I've searched up but I do not understand other people's code. I will appreciate if you can edit from my code and guide me through explanation. Thank you

#include <stdio.h>
int main(void)
{
    int x,y,z;

    printf("Input a number: ");
    scanf("%d", &x);

      for (z=2; z<=50; z++)
        {
            for (y=2; y<=z; y++)
            {
                if (z%y==0)
                    break;
            }
            if (z==y)
            printf("%d\n", z);
            
        }
}

Solution

  • Add a "prime number counter"

    #include <stdio.h>
    int main(void)
    {
        int x,y,z;
        int primes = 0; // no primes found so far
    
        printf("Input a number: ");
        scanf("%d", &x);
    
          for (z=2; z<=50; z++)
            {
                for (y=2; y<=z; y++)
                {
                    if (z%y==0)
                        break;
                }
                if (z==y) {
                    printf("%d\n", z);
                    primes += 1; // found a prime
                }
    
                if (primes == x) break; // stop z loop after x primes
                
            }
    }