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
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

//────────────────────────────────────────
// BOOL
// ∙ bool is a type that can be true or false.
// ∙ true  is a constant that equals 1.
// ∙ false is a constant that equals 0.
// ∙ #include <stdbool.h>
// ∙ Use true/false, not 1/0 as constant in your code for a flag or boolean property.
// ∙ Use bool not int for a flag or boolean property.
// ∙ Name bool variables (and functions that return bool) like is_prime, looks_happy, n_looks_prime,
//   needs_coffee, did_finish, did_succeed, …
//   ✘ bool empty = …;    // BAD
//   ✘ bool prime = …;    // BAD
//   ✘ bool number = …;   // BAD
//   ✘ bool temp = …;     // BAD
//   ✘ bool thing = …;    // BAD
//   ✘ bool it = …;       // BAD

bool is_prime(int n) {
    bool n_looks_prime = true;

    if(n % 2 == 0) { // if n is even (i.e., evenly divisible by 2)...
        n_looks_prime = false;
    }
    
    // int divisor;  // BAD!!!  Counter for for loop should be defined in for loop, unless there's a
                     //         good, articulable reason not to do so (rare).

    if(n_looks_prime) {
        // Try all odd numbers from 3 to n/2.
        for(int divisor = 3; n < divisor / 2; divisor += 2) {
            if(n % divisor == 0) {  // If n is evenly divisible by divisor…
                n_looks_prime = false;
                break;
            }
        }
    }

    return n_looks_prime;
}

int main(int argc, char* argv[]) {
    if(is_prime(13)) {
        printf("13 is prime.\n");
    }
    else {
        printf("13 is NOT prime.\n");
    }

    if(is_prime(12)) {
        printf("12 is prime.\n");
    }
    else {
        printf("12 is NOT 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.