Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Prime number generator (See related posts)

This program will calculate & list the first n primes, where n is a number specified on the command line or (if none is specified) 100. n is only limited by the size of ints on your platform.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char** argv) {
 int qty = (argc > 1) ? (int) strtol(argv[1], NULL, 10) : 100;
 if (qty < 3) qty = 100;
 unsigned int primes[qty];
 primes[0] = 2U; primes[1] = 3U;
 printf("2\n3\n");
 for (int i=2; i<qty; i++) {
  int j = primes[i-1];
  iter: j += 2U;
  unsigned bound = (unsigned) sqrt((double) j);
  for (int k=1; k<i; k++) {
   if (primes[k] > bound) break; /*Not a viable shortcut for small quantities*/
   if (!(j % primes[k])) goto iter;
  }
  primes[i] = j;
  printf("%u\n", j);
 }
 return 0;
}

You need to create an account or log in to post comments to this site.


Click here to browse all 5201 code snippets

Related Posts