Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Find the sum of all the multiples of 3 or 5 below 1000.
Problem 1 is the first and the easiest problem in the collection.
There are multiple ways of solving this, and I will introduce two main ways.
First way, which I didn't use in my code, is to brute force through the entire 1000 numbers.
You may use for-loop from i = 1 up to i < 1000 and check if i % 3 == 0 || i % 5 == 0
Second way, which I used in my code, is to use formula for consecutive sum.
The formula for adding from 1 to integer n is n (n+1) / 2
Also, using set property,
(multiple of 3) or (multiple of 5) = (multiple of 3) + (multiple of 5) - (multiple of 3 and 5)
Sum of multiples of 3 under 1000 would be
3 + 6 + 9 + 12 + 15 + ... + 999 = 3 * (1 + 2 + 3 + 4 + 5 + ... + 333) = 3 * (sum from 1 to 333)
= 3 * (333 * 334 / 2) = 166833
Using same formula, we will get 166833 + 99500 - 33165 = 233168
This was one of few problems that could be solved by hand with basic algebra.
Answer is 233168
Execution time is 0.8 ms, or 0.0008 seconds
Source code: https://github.com/Ainodyne/Project-Euler/blob/master/Problem001.java
Also, using set property,
(multiple of 3) or (multiple of 5) = (multiple of 3) + (multiple of 5) - (multiple of 3 and 5)
Sum of multiples of 3 under 1000 would be
3 + 6 + 9 + 12 + 15 + ... + 999 = 3 * (1 + 2 + 3 + 4 + 5 + ... + 333) = 3 * (sum from 1 to 333)
= 3 * (333 * 334 / 2) = 166833
Using same formula, we will get 166833 + 99500 - 33165 = 233168
public static int sumMultiple(int divisor, int num) { int last = num/divisor; int sum = (last*(last + 1))/2; return sum*divisor; }
This was one of few problems that could be solved by hand with basic algebra.
Answer is 233168
Execution time is 0.8 ms, or 0.0008 seconds
Source code: https://github.com/Ainodyne/Project-Euler/blob/master/Problem001.java
No comments:
Post a Comment