number_facts.c in C
A complete program: read numbers from argv, report facts about each.
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int is_prime(long n) {
if (n < 2) {
return 0;
}
for (long d = 2; d * d <= n; d++) {
if (n % d == 0) {
return 0;
}
}
return 1;
}
static int digit_sum(long n) {
int total = 0;
if (n < 0) {
n = -n;
}
while (n > 0) {
total += (int) (n % 10);
n /= 10;
}
return total;
}
static int parse_long(const char *text, long *out) {
errno = 0;
char *end = NULL;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return 0;
}
if (errno == ERANGE || value > INT_MAX || value < INT_MIN) {
return 0;
}
*out = value;
return 1;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s NUMBER...\n", argv[0]);
return 1;
}
printf("%-12s %6s %5s %9s\n", "value", "prime", "even", "digitsum");
long total = 0;
for (int i = 1; i < argc; i++) {
long value = 0;
if (!parse_long(argv[i], &value)) {
fprintf(stderr, "skipping %s: not a number\n", argv[i]);
continue;
}
total += value;
printf("%-12ld %6s %5s %9d\n", value,
is_prime(value) ? "yes" : "no",
value % 2 == 0 ? "yes" : "no",
digit_sum(value));
}
printf("total %ld across %d arguments\n", total, argc - 1);
return 0;
}
How it works
argcandargvcarry the command line, program name first.strtolreports both the value and where it stopped parsing.- The program returns non-zero when it was given nothing to do.
Keywords and builtins used here
NULLcharconstcontinuedigit_sumforifintis_primelongmainparse_longreturnstaticwhile
The run, in numbers
- Lines
- 71
- Characters to type
- 1223
- Tokens
- 407
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 244 seconds.
Step 3 of 3 in Encore, step 35 of 35 in Language basics.