aboutsummaryrefslogtreecommitdiff
path: root/challenge-012/paulo-custodio/cpp/ch-1.cpp
blob: b18ecaaa19e777a872223aa0e76a231c8d3edd31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Challenge 012

Challenge #1
The numbers formed by adding one to the products of the smallest primes are
called the Euclid Numbers (see wiki). Write a script that finds the smallest
Euclid Number that is not prime. This challenge was proposed by
Laurent Rosenfeld.
*/

#include <iostream>
using namespace std;

bool is_prime(int n) {
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
    if ((n % 2) == 0 || (n % 3) == 0)
        return false;
    for (int i = 5; i * i <= n; i += 6)
        if ((n % i) == 0 || (n % (i + 2)) == 0)
            return false;
    return true;
}

int next_prime(int n) {
    if (n <= 1)
        return 2;
    do {
        n++;
    } while (!is_prime(n));
    return n;
}

int next_euclid(void) {
    static int prime = 1;
    static int prime_prod = 1;

    prime = next_prime(prime);
    prime_prod *= prime;
    return prime_prod + 1;
}

int main(void) {
    int euclid;
    while (is_prime(euclid = next_euclid()))
        ;
    cout << euclid << endl;
}