I was in kind of hurry, I didn't translate the code well. That example won't work but I can't edit it now. I post it here here hoping one of our moderators will delete it and put it in previous post.
whiteflags,
Thanks for your reply, but why billion buses and very long tours? Suppose we take 5 buses. They make tours in 71, 73, 79, 83, 89 minutes.The result will easy exceed the boundaries of an int since the lcm is 3024658859 or 2100457 days and 54 hours.
I would like to understand the strategies or programming habits in such as situations.
Solution without using LCM(LCM(x,y),z) .. and so on.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int nbuses = argc - 1; // number of buses
int buses[nbuses]; // list of buses
int lcm = 0; //lcm to find
int product = 1; //assume all are prime numbers
int max = 1; //largest tour
int i = 0;
while (i < nbuses) {
int num;
if ((sscanf(argv[i+1], "%d", &num) == 1)) {
buses[i] = num;
i++;
} else {
fprintf(stderr, "Not a number.\n");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < nbuses; i++) {
product*=buses[i];
if (buses[i] > max) {
max = buses[i];
}
}
while (max < product) {
int tmp = 0;
i = 0;
while (i < nbuses) {
if (max % buses[i] == 0) {
tmp++;
i++;
if (tmp == nbuses) {
lcm = max;
max = product;
}
} else {
max++;
tmp = 0;
i = 0;
continue;
}
}
}
printf("LCM is: %d.", lcm);
return 0;
}