Question: 2520 is the smallest number that can be divided into each of the numbers from 1 to 10 without a remainder.
What is the smallest positive number evenly divided by all numbers from 1 to 20?
So, I tried to do exercise 5 on the 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\n", i, count); if (count == 0) { fnd = TRUE; printf ("%d\n", i); } } return 0; }
I believe my apporach is correct, it will surely find a number that is divisible by 1-20. But it was calculated within 5 minutes and still no result. Is my approach right? If so, is there another way to do this? I can not think differently to solve this, the tips will be very much appreciated. Thank you in advance.
EDIT: So, based on the advice I gave you guys, I figured it out, thank you so much! Thus, this is still brute force, but instead of adding 1 to the last number, 2520 is now added, that is, LCM from 1 to 10. And, therefore, calculating if the sum of the residues is a multiple of 2520 is divided by 11 20 was 0. Since 2520 is already divided by 1-10, I needed to divide by 11-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\n", i, count); if (count == 0 && i != 0) { fnd = TRUE; printf ("%d\n", i); } } return 0; }
Thank you so much, I would not have resolved this without your help :) PS: now it calculates in less than 10 seconds.