From 87291b54e54099033a9720e706e811aafb2aba9e Mon Sep 17 00:00:00 2001 From: Mia Herkt Date: Mon, 12 Dec 2022 00:08:30 +0100 Subject: [PATCH] 11: C: Get LCM by prime factorization --- 11/solution.c | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/11/solution.c b/11/solution.c index a37272d..6c838da 100644 --- a/11/solution.c +++ b/11/solution.c @@ -1,6 +1,7 @@ #include #include #include +#include typedef struct Monkey { unsigned long business; @@ -20,15 +21,37 @@ int compar(const void *a, const void *b) { return 0; } +unsigned long calc_lcm(Monkey *monkeys, int count) { + unsigned long lcm = 1; + + for (int m = 0; m < count; m++) { + unsigned long v = monkeys[m].test; + + while (!(v % 2)) { + lcm *= 2; + v /= 2; + } + + for (unsigned long i = 3; i <= sqrt(v); i += 3) { + while (!(v % i)) { + lcm *= i; + v /= i; + } + } + + if (v > 2) + lcm *= v; + } + + return lcm; +} + unsigned long monkey_business(Monkey *monkeys, int count, int steps, int part2) { Monkey *copy = malloc(count * sizeof(Monkey)); memcpy(copy, monkeys, count * sizeof(Monkey)); monkeys = copy; - unsigned long lcm = 1; - if (part2) - for (int m = 0; m < count; m++) - lcm *= monkeys[m].test; // these are all primes + unsigned long lcm = part2 ? calc_lcm(monkeys, count) : 0; for (int s = 0; s < steps; s++) { for (int m = 0; m < count; m++) { @@ -43,8 +66,7 @@ unsigned long monkey_business(Monkey *monkeys, int count, int steps, int part2) case '*': new *= val; break; } - if (part2) new %= lcm; - else new /= 3; + new = part2 ? new % lcm : new / 3; int target = monkeys[m].true; if (new % monkeys[m].test)