DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Prime Number Generator

  • submit to reddit
        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;
 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;