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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#define ENABLE_DEBUGGING_CODE
// Define a “symbol” ENABLE_DEBUGGING_CODE
// #ifdef happens at COMPILE TIME, not when your program is running.
#ifdef ENABLE_DEBUGGING_CODE
// ENABLE
# define dbg_log_int(n) (printf("# %s == %d\n", (#n), (n)))
// Reminder: #n means the text of the expression passed to the function-like macro.
#else
// DISABLE
# define dbg_log_int(n)
// Invocations to the function-like macro disappear.
// ∙ dbg_log_int(divisor); ⇒ ;
#endif
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."
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.