Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your approach is taking too long because it is a brute-force solution. You need to be slightly clever.

My hint for you is this: What does it mean for a number to be evenly divisible by another number? Or every number below a certain number? Are there commonalities in the prime factors of the numbers? The Wikipedia page on divisibility should be a good starting point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...