Tuesday, April 14, 2015

HackerRank::Contests::ProjectEuler::Project Euler #1: Multiples of 3 and 5

   A few things to notice here after which the task will become very easy to solve. Here is a quick question , how many numbers are there from 1 to N that are divisible by 3 ? Simple right? It's N/3 (divide and throw away the remainder). In that case, how to calculate their sum?
3+6+9+...3*M = 3( 1+2+3+...+M). which is equal to (3 * M * (M+1)) /2 (M is the number of numbers in the sequence). The same goes for 5.
   Now we have calculated the sum of all number that are divisible by 3, and we have calculated the sum of all number that are divisible by 5. There are some numbers which are divisible by 15 (both 3 and 5) and we counted them twice , the first time we counted them as a multiple of 3 and the second time we counted it as a multiple of 5. That's why we need to subtract the sum of all number from 1 to N that are divisible by 15 in order to get the final answer.



No comments:

Post a Comment