11: C: Get LCM by prime factorization
This commit is contained in:
parent
05f53d07c8
commit
b38eab7062
|
@ -1,6 +1,7 @@
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
typedef struct Monkey {
|
typedef struct Monkey {
|
||||||
unsigned long business;
|
unsigned long business;
|
||||||
|
@ -26,9 +27,23 @@ unsigned long monkey_business(Monkey *monkeys, int count, int steps, int part2)
|
||||||
monkeys = copy;
|
monkeys = copy;
|
||||||
|
|
||||||
unsigned long lcm = 1;
|
unsigned long lcm = 1;
|
||||||
if (part2)
|
if (part2) {
|
||||||
for (int m = 0; m < count; m++)
|
for (int m = 0; m < count; m++) {
|
||||||
lcm *= monkeys[m].test; // these are all primes
|
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 s = 0; s < steps; s++) {
|
||||||
for (int m = 0; m < count; m++) {
|
for (int m = 0; m < count; m++) {
|
||||||
|
|
Loading…
Reference in New Issue