Sum of Multiples of 3, 5, and 7
In this lab, you will be working on a function sumOfMultiples
which takes a positive integer n
and returns the sum of all integers in the range [1, n]
inclusive that are divisible by 3
, 5
, or 7
.
You have to ensure your solution follows ESM import/export and is free of bugs. The function and any additional code needed for testing must be exported.
Examples
Example 1:
sumOfMultiples(7); // output: 21
In the range [1, 7]
, the numbers divisible by 3, 5, or 7 are 3, 5, 6, 7
. The sum of these numbers is 21
.
Example 2:
sumOfMultiples(10); // output: 40
In the range [1, 10]
, the numbers divisible by 3, 5, or 7 are 3, 5, 6, 7, 9, 10
. The sum of these numbers is 40
.
Example 3:
sumOfMultiples(9); // output: 30
In the range [1, 9]
, the numbers divisible by 3, 5, or 7 are 3, 5, 6, 7, 9
. The sum of these numbers is 30
.
Constraints
1 <= n <= 103
Challenges
- Export the
sumOfMultiples
function. - Implement the
sumOfMultiples
function.
Here is the evaluation script you need to complete and include in the final solution:
1import fs from 'fs' 2 3// testlog is a log of test results 4const testlog = [] 5 6// this first block matches with - Challenge 1 7try { 8 const sumOfMultiples = await import('/home/damner/code/index.js').then(t => t.sumOfMultiples) 9 10 // perform some testing 11 if(typeof sumOfMultiples === 'function') { 12 testlog.push({ status: 'pass' }) 13 } else { 14 throw new Error('sumOfMultiples is not exported as a function') 15 } 16} catch(error) { 17 testlog.push({ 18 status: 'error', 19 error: error.message || 'Challenge failed' 20 }) 21} 22 23// this second block matches with - Challenge 2 24try { 25 const sumOfMultiples = await import('/home/damner/code/index.js').then(t => t.sumOfMultiples) 26 27 // perform some testing 28 const testCases = [ 29 { input: 7, output: 21 }, 30 { input: 10, output: 40 }, 31 { input: 9, output: 30 } 32 ] 33 34 testCases.forEach(test => { 35 if(sumOfMultiples(test.input) === test.output) { 36 testlog.push({ status: 'pass' }) 37 } else { 38 throw new Error(`Expected ${test.output} but got ${sumOfMultiples(test.input)}`) 39 } 40 }) 41} catch(error) { 42 testlog.push({ 43 status: 'error', 44 error: error.message || 'Challenge failed' 45 }) 46} 47 48// very important for the final length of `testlog` array to match the number of challenges, in this case - 2. 49 50// write the test log 51fs.writeFileSync('/home/damner/code/.labtests/testlog.json', JSON.stringify(testlog)) 52 53// write the results array boolean. this will map to passed or failed challenges depending on the boolean value at the challenge index 54fs.writeFileSync(process.env.UNIT_TEST_OUTPUT_FILE, JSON.stringify(testlog.map(result => result.status === 'pass')))
Make sure to keep all rules in mind while completing the lab, including the length of the testlog
array, order of try-catch blocks, and other mentioned points.