Sum of Multiples of 3 and 5
- Time:2020-09-10 12:55:33
- Class:Weblog
- Read:23
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.
Let’s declare a Javascript function to sum up all the numbers that are the multiples of 3 or 5.
1 2 3 4 5 6 7 8 9 | function sumOfMultiplesThreeAndFive(n) { let sum = 0; for (let i = 1; i < n; ++ i) { if ((i % 3 == 0) || (i % 5 == 0)) { sum += i; } } return sum; } |
function sumOfMultiplesThreeAndFive(n) { let sum = 0; for (let i = 1; i < n; ++ i) { if ((i % 3 == 0) || (i % 5 == 0)) { sum += i; } } return sum; }
Calling this function with input 1000 gives us the answer of 233168.
The runtime complexity of the above Javascript code is O(N) and the space requirement is O(1) constant.
Another modern Javascript implementation based on Map and Reduce:
1 2 3 4 5 | function sumOfMultiplesThreeAndFive(n) { return [...Array(n - 1).keys()].map(i =>i+1). filter(x => (x%3==0||x%5==0)). reduce((x, y) => x + y, 0); } |
function sumOfMultiplesThreeAndFive(n) { return [...Array(n - 1).keys()].map(i =>i+1). filter(x => (x%3==0||x%5==0)). reduce((x, y) => x + y, 0); }
–EOF (The Ultimate Computing & Technology Blog) —
Recommend:5 Best Instagram Marketing Strategies for Blogs
Want to Generate More Engagement on Twitter?
4 Handy Tips for Bloggers Exploring a New Industry
3 Ambitious Blog Subjects for Small Businesses
How to Write Fresh Blog Content After Years on the Job
5 Clean Energy Blogs to Read in 2019
Social Media is Dying. Here are 3 Ways to Hack it for More Traff
5 Skills All Successful Content Writers Have Mastered
Blogging for Dummies in 2019: The Only Cheat Sheet You Need
Are Readers Reaching Your Call To Action?
- Comment list
-
- Comment add