Skip to content

Instantly share code, notes, and snippets.

@Flygsand
Created June 27, 2023 21:29
Show Gist options
  • Save Flygsand/eaad934deeeee62fa8f1f82aa7ac086b to your computer and use it in GitHub Desktop.
Save Flygsand/eaad934deeeee62fa8f1f82aa7ac086b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int digitalroot(long num) {
int sum = 0;
// sum digits of num
while (num > 0) {
sum += num % 10;
num = num / 10;
}
// reduce sum to digital root
while (sum > 9) {
sum = (sum / 10) + (sum % 10);
}
return sum;
}
int isdigitalroot(long num, int dr) {
return num >= dr && (num - dr) % 9 == 0;
}
void print_combos_of_3(int dr) {
for (int a = 1; a <= 8; a++) {
for (int b = a + 1; b <= 8; b++) {
for (int c = b + 1; c <= 8; c++) {
if (isdigitalroot(a + b + c, dr)) {
printf("%d + %d + %d -> %d\n", a, b, c, dr);
}
}
}
}
}
void print_combos_of_4(int dr) {
for (int a = 1; a <= 8; a++) {
for (int b = a + 1; b <= 8; b++) {
for (int c = b + 1; c <= 8; c++) {
for (int d = c + 1; d <= 8; d++) {
if (isdigitalroot(a + b + c + d, dr)) {
printf("%d + %d + %d + %d -> %d\n", a, b, c, d, dr);
}
}
}
}
}
}
void print_combos_of_5(int dr) {
for (int a = 1; a <= 8; a++) {
for (int b = a + 1; b <= 8; b++) {
for (int c = b + 1; c <= 8; c++) {
for (int d = c + 1; d <= 8; d++) {
for (int e = d + 1; e <= 8; e++) {
if (isdigitalroot(a + b + c + d + e, dr)) {
printf("%d + %d + %d + %d + %d -> %d\n", a, b, c, d, e, dr);
}
}
}
}
}
}
}
void print_usage() {
fprintf(stderr, "usage: digitalroot [-c <count>] <num>\n");
}
int main(int argc, char *argv[]) {
char *end;
if (argc == 4 && strcmp(argv[1], "-c") == 0) {
int count = strtol(argv[2], &end, 10);
if (end == argv[3] || *end != '\0' || count < 3 || count > 5) {
fprintf(stderr, "error: <count> must be a number between 3 and 5\n");
return 2;
}
int dr = strtol(argv[3], &end, 10);
if (end == argv[3] || *end != '\0' || dr < 1 || dr > 9) {
fprintf(stderr, "error: <num> must be a number between 1 and 9\n");
return 2;
}
if (count == 3) {
print_combos_of_3(dr);
} else if (count == 4) {
print_combos_of_4(dr);
} else if (count == 5) {
print_combos_of_5(dr);
}
} else if (argc == 2) {
errno = 0;
long num = strtol(argv[1], &end, 10);
if (end == argv[1] || *end != '\0' || num < 0 || num == LONG_MAX && errno == ERANGE) {
fprintf(stderr, "error: <num> must be a positive number\n");
return 2;
}
printf("%s -> %d\n", argv[1], digitalroot(num));
} else {
print_usage();
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment