|
1 | 1 | // https://projecteuler.net/problem=1
|
2 |
| -/* Multiples of 3 and 5 |
3 |
| - 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. |
| 2 | +/* Multiples of 3 and 5 |
| 3 | +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. |
4 | 4 | Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
|
5 | 5 | */
|
6 | 6 |
|
7 |
| -//nSum function calculates the sum of first n numbers in the table of number num |
8 |
| -//here n is denoted as frequency |
| 7 | +// This method uses the nSum function to add the nSum for 3 and 5. However, it needs to subtract the nSum for 15 once to avoid double counting. |
| 8 | +const multiplesThreeAndFive = num => { |
| 9 | + if (num < 1) throw new Error('No natural numbers exist below 1') |
| 10 | + num -= 1 |
| 11 | + let sum = 0 |
9 | 12 |
|
| 13 | + // The nSum function calculates the sum of the first n numbers in the sequence with a common difference of num. |
| 14 | + // Here, n is denoted as frequency. |
| 15 | + const nSum = (num, frequency) => (frequency * (frequency + 1) * num) >> 1 |
10 | 16 |
|
11 |
| -//this method uses the nSum function adds the nSum for 3 and 5 but due to this nSum for 15 has been automatically added twice so it needs to be removed once |
12 |
| -const multiplesThreeAndFive = (num) => { |
13 |
| - if (num < 1) throw new Error('No natural numbers exist below 1') |
14 |
| - num-=1; |
15 |
| - let sum = 0 |
16 |
| - |
17 |
| - const nSum = (num,frequency)=>{ |
18 |
| - return frequency*(frequency+1)*num>>1 |
19 |
| - } |
20 |
| - sum += nSum(3,Math.floor(num/3)); |
21 |
| - sum += nSum(5,Math.floor(num/5)); |
22 |
| - sum -= nSum(15,Math.floor(num/15)); |
23 |
| - return sum |
| 17 | + sum += nSum(3, Math.floor(num / 3)) |
| 18 | + sum += nSum(5, Math.floor(num / 5)) |
| 19 | + sum -= nSum(15, Math.floor(num / 15)) |
| 20 | + return sum |
24 | 21 | }
|
25 | 22 |
|
26 |
| - |
27 |
| -export { multiplesThreeAndFive } |
| 23 | +export {multiplesThreeAndFive} |
0 commit comments