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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#define dbg_log_int(n) (printf("# %s == %d\n", (#n), (n)))
#define dbg_printf(...) (printf(__VA_ARGS__))
// Reminder: #n means the text of the expression passed to the function-like macro.
// ... and __VA_ARGS__ are for a variadic macro (different from variadic function in HW05).
// They pass any/all arguments to the rhs of the macro.
// #define dbg_log_int(n)
// #define dbg_printf(...)
//
// Invocations to the function-like macro disappear.
// ∙ dbg_log_int(divisor); ⇒ ;
bool is_prime(int n) {
bool n_looks_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(n_looks_prime) {
for(int divisor = 3; divisor < n / 2; divisor += 2) {
// printf("# divisor == %d\n", divisor); // debugging output
dbg_log_int(divisor);
dbg_printf("n == %d divisor == %d\n", n, divisor);
assert(divisor % 2 == 1); // "I claim that divisor must be odd."
if(n % divisor == 0) {
n_looks_prime = false;
break;
}
}
}
assert(n == 2 || n % 2 == 1 || n_looks_prime == false); // "I claim that n cannot be prime and even unless n is 2."
assert(n == 2 || n % 2 == 1 || ! n_looks_prime); // "I claim that n cannot be prime and even unless n is 2."
return n_looks_prime;
}
int main(int argc, char* argv[]) {
int n = 13;
if( is_prime(n) ) {
printf("%d is prime", n); // REQUIRED OUTPUT (by specification for program)
}
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.