Jeremiah Mahler

home

Find First 100 Prime Numbers

17 Jan 2014

Question

Write a C program to find the first 100 prime numbers.

Answer

Recall that a prime number is a positive number larger than one whose only divisors are 1 and itself.

The following was developed on a computer which allowed it to be quickly tested. Accomplishing this using only a white board is much more difficult.

#include <stdio.h>

int main() {
    
    const unsigned int max = 100;  // number of primes to find

    unsigned int found[max];
    unsigned int count = 0;       // number found so far

    unsigned int cur = 2;         // current prime

    unsigned int i;
    unsigned int found_one;

    while (count < max) {
        found_one = 1;  // default true
        for (i = 2; i < cur; i++) {
            if (0 == (cur % i)) {
                found_one = 0;  // fail
                break;
            }
        }

        if (found_one) {
            found[count++] = cur;
        }

        cur++;
    }

    for (i = 0; i < max; i++) {
        printf("%i\n", found[i]);
    }

    return 0;
}

Background

This question was given during an interview on 1/17/2014 for a firmware test engineer position.