# Robson » Code » C++ » Primes

`#include <stdio.h>`
` `
`// the highest prime number to check`
`// if this was 10, the prime numbers 2, 3, 5 and 7 would be found`
`#define MAX_PRIME 100`
` `
`// this stores the prime numbers`
`int primes[MAX_PRIME];`
` `
`// this is the number of primes found`
`int p_count = 2;`
` `
`// this function finds the prime numbers`
`int prime_numbers(int max)`
`{`
`    bool bPrime, bSwitch = false;`
`    primes[0] = 2;`
`    primes[1] = 3;     `
`    for (int a = 5; a <= max; a+=2)`
`    {`
`        bPrime = true;`
`        for (int b = 0; b < p_count; b++)`
`        {`
`            if (primes[b] * primes[b] > a)`
`                break;`
`            if (!(a % primes[b]))`
`            {`
`                bPrime = false;`
`                break;`
`            }  `
`        }          `
`        if (bPrime)`
`            primes[p_count++] = a;`
`        if (bSwitch)`
`           a+=2;`
`        bSwitch = !bSwitch;`
`    }`
`} `
` `
`// * example use - print all prime numbers found to the console * //`
`int main()`
`{`
`    prime_numbers(MAX_PRIME);`
`    for (int n = 0; n < p_count; n++)`
`        printf("%d, ", primes[n]);`
`}`

© 2004-19 robson | cc unless stated