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)
(요약) 주어진 숫자 미만 요소 중 3의 배수와 5의 배수를 구해서 다 더해라.
function solution(number){ const belowNum = number - 1; const arr = [Math.floor(belowNum / 3), Math.floor(belowNum / 5), Math.floor(belowNum / 15)]; return sum(arr[0], 3) + sum(arr[1], 5) - sum(arr[2], 15); } function sum(n, m) { return n * (n + 1) / 2 * m; }
답을 구하는 방법은 3과 5의 등차수열의 합에서 15의 등차수열의 합을 빼면 된다.
빼는 이유는 3과 5의 배수를 구하다보면 15의 배수가 한 번 중복 계산되기 때문이다.
임시 배열
arr
에 3의 배수의 개수, 5의 배수의 개수, 15의 배수의 개수를 구한다.개수를 구하는 이유는 각 등차수열의 요소를 몇 번째까지 더하느냐를 구하기 위해서다.
등차수열의 합을 구하는 함수
sum
을 만들어서 계산하고return
하면 끝.