diff --git a/11/solution.c b/11/solution.c index a37272d..a59f052 100644 --- a/11/solution.c +++ b/11/solution.c @@ -1,6 +1,7 @@ #include #include #include +#include typedef struct Monkey { unsigned long business; @@ -26,9 +27,23 @@ unsigned long monkey_business(Monkey *monkeys, int count, int steps, int part2) monkeys = copy; unsigned long lcm = 1; - if (part2) - for (int m = 0; m < count; m++) - lcm *= monkeys[m].test; // these are all primes + if (part2) { + 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; + } + } for (int s = 0; s < steps; s++) { for (int m = 0; m < count; m++) {