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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

#include "my_debugging_tools.h"
#include "dbg_log.h"

bool is_prime(int n) {
    bool is_n_prime = (n % 2) != 0;  // Assume n is prime unless we find that it is divisible
                                     // by something other than 1 or itself.

    // Try all ODD numbers from 3 to n/2
    if(is_n_prime) {
        for(int divisor = 3; divisor < n / 2; divisor += 2) {
            dbg_log_int(divisor);
            assert(divisor % 2 == 1);  // "I claim that divisor must be odd."
            if(n % divisor == 0) {
                is_n_prime = false;
                break;
            }
        }
    }

    assert(n == 2 || n % 2 == 1 || is_n_prime == false);  // "I claim that n cannot be prime and even unless n is 2."
    assert(n == 2 || n % 2 == 1 || ! is_n_prime);         // "I claim that n cannot be prime and even unless n is 2."

    if(is_n_prime) {
        dbg_printf("# Looks like %d is prime.", n);
    }
    return is_n_prime;
}

int main(int argc, char* argv[]) {
    int n = 13;
    if( is_prime(n) ) {
        printf("%d is prime", n);
    }
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2021 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.