Created
June 5, 2011 12:37
-
-
Save nefarioustim/1008926 to your computer and use it in GitHub Desktop.
Find the sum of all the multiples of 3 or 5 below 1000.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Do the maths | |
for( | |
var sum = 0, i = 1; | |
i < 1000; | |
!(i % 3 && i % 5) && (sum += i), i++ | |
); | |
// Log the result | |
console.log(sum); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prep the array | |
for( | |
var arr = [], i = 1; | |
i < 1000; | |
!(i % 3 && i % 5) && arr.push(i), i++ | |
); | |
// Sum the array | |
console.log( | |
arr.reduce( | |
function(prev, current) { | |
return prev + current | |
} | |
) | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print sum([i for i in range(1000) if not (i % 3 and i % 5)]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts (1...1000).select{ |n| n % 3 == 0 || n % 5 == 0 }.reduce(:+) |
Actually Dave, can you do it again using only 1000, 3, and 5 as parameters?
Your maths is wrong 'cos whilst 999 is valid for 3, it should be 995 for 5 and… uh… 990 for 15, I believe.
For those that are interested, problem 2 solved with JS here: https://gist.github.com/1009018
(999 / 15) * 15 = 990
(999 / 15.0) * 15 = 998.9999
Integer truncation is my friend
Here is one that solves the sum of multiples of numbers in an array less than a given limit.
Find the codein JS HERE
//test: find the sum of the multiples of 3 and 5 less than 1000
console.log(sumOfMultplesOfNumbersLessThan([3,5], 1000));
sum = 0;
for(i = 1; i<1000;i++){
if((i % 3 === 0) || (i % 5 ===0)){
sum += i;
}
}
newbie rules!
Super useful. thanks for posting this with the different code options.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nah, that's the algebraic solution to the problem. I remember doing that at school. :D