Question: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
So, I was trying to do exercise 5 on project euler and I came out with this code:
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main () {
int n, fnd = FALSE, count, i;
for (i = 1; fnd == FALSE; i++) {
count = 0;
for (n = 1; n <= 20; n++) {
count += i % n;
}
printf ("testing %d, count was: %d
", i, count);
if (count == 0) {
fnd = TRUE;
printf ("%d
", i);
}
}
return 0;
}
I believe my apporach is correct, it will surely find the number which is divisible by 1 to 20. But it's been computing for 5 minutes, and still no result. Is my approach correct? If yes, then is there another way to do it? I can't think on another way to solve this, tips would be very much appreciated. Thank you in advance.
EDIT:
So, based on the advice I was given by you guys I figured it out, thank you so much!
So, it's still brute force, but instead of adding 1 to the last number, it now adds 2520, which is the LCM of 1 to 10. And therefore, calculating if the sum of the remainders of the multiples of 2520 divided from 11 to 20 was 0. Since 2520 is already divisible by 1 to 10, I only needed to divide by 11 to 20.
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main () {
int n, fnd = FALSE, count, i;
for (i = 2520; fnd == FALSE; i = i + 2520) {
count = 0;
for (n = 11; n <= 20; n++) {
count += i % n;
}
printf ("testing %d, count was: %d
", i, count);
if (count == 0 && i != 0) {
fnd = TRUE;
printf ("%d
", i);
}
}
return 0;
}
Thank you so much, I wouldn't solve it without your help : )
PS: It now computes in less than 10 secs.
See Question&Answers more detail:
os