Sum of Multiples of 3 and 5
- 时间:2020-09-10 12:55:33
- 分类:网络文摘
- 阅读:120 次
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) —
推荐阅读:数学题:服装厂的工人每人每天可以生产4件上或7条裤子 数学题:一个长方体长,宽,高都是两位数,并且它们的和是偶数 数学题:若115,200,268被大于1的自然数除 数学题:一只蚂蚁从墙根竖直向上爬到墙头用了4分钟 一位农妇上午挎了一个空篮子笑眯眯地回家 奥数题:秋游时,小红小玲小芳三个好朋友在一个小组一起活动 平年和闰年自测题 数学题:李爷爷家住在半山腰 数学题:无线电元件厂验收一批零件 数学题:调查发现,该学校七年级参加魔方比赛的学生中
- 评论列表
-
- 添加评论