Don't say so much, just coding...
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.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once. Also, if a number is negative, return 0(for languages that do have them)
def solution(number)
# put your solution here
end
def test(actual, expected)
Test.assert_equals(actual, expected)
end
Test.describe("example tests") do
test(solution(10), 23)
test(solution(20), 78)
test(solution(200), 9168)
end
function solution(number){
// put your solution here
}
function test(n, expected) {
let actual = solution(n)
Test.assertEquals(actual, expected, `Expected ${expected}, got ${actual}`)
}
Test.describe("basic tests", function(){
test(10,23)
})
想法(1): 從題目概述 natural numbers below 10
中開始模擬會出現的數字
想法(2): 計算兩者的加總,可以知道在算 3 or 5 的倍數
想法(3): 處理級距,需要從 1 ~ 參數
然後再來選取符合項目,並加總
# Solution 1
def solution(number)
[*1..number-1].select{ |n| n % 3 == 0 || n % 5 == 0}.reduce(&:+)
end
# Solution 2
def solution(number)
[*1...number].select{ |n| n % 3 == 0 || n % 5 == 0}.reduce(&:+)
end
# Solution 3
def solution(number)
(1...number).select{ |n| n % 3 == 0 || n % 5 == 0}.inject(&:+)
end
# Solution 4
def solution(number)
(1...number).select{ |n| (n % 5).zero? || (n % 3).zero?}.inject(:+)
end
// Solution 1
function solution(number){
let sum = 0;
for(i = 1; i < number; i++){
if( i % 3 == 0 || i % 5 == 0){
sum += i;
}
}
return sum;
}
// Solution 2
function solution(number){
return number < 3 ? 0
: [...Array(number).keys()]
.map(k => (k % 3 === 0 || k % 5 === 0) ? k : 0 )
.reduce((sum, num) => sum + num )
}