This problem on codewars asks the following:
A function should return the sum of all the multiples of 3 or 5 below a given number. If the number is negative, return 0. For numbers that are multiples of both 3 and 5, count them only once.
Example: (Input --> Output)
solution(10) = 23
solution(-1) = 0
solution(15) = 45 (Not including 15)
How to approach it with the PEDAC method:
P: Understand the problem -
The task is to compute the sum of all numbers below a given number that are multiples of 3 or 5, treating negatives as a special case where the result is always 0.
E: Give Example -
For a number like 10, you’d get 3, 5, 6, and 9 as the multiples, summing up to 23.
For -1, since it's negative, the result should be 0.
D: What data structure(s) would be needed -
You can simply use a variable to accumulate the total sum; no complex data structure is required.
A: Steps to solve it without language specific information -
- Initialize a sum variable at 0.
- If the input number is negative, return 0 immediately.
- Loop through numbers starting from 1 up to but not including the input number.
- For each number, check if it's a multiple of 3 or 5.
- If it is, add it to the sum.
- Return the sum after the loop.
C: The final code using the pseudocode (A) to guide me -
- Initialize sum and handle negative input
function solution(number){
let total = 0;
if(number < 0){ return 0}
}
- Loop through numbers and check for multiples of 3 or 5
function solution(number){
let total = 0;
if(number < 0){ return 0}
for(let i = 1; i < number; i++){
if(i % 3 === 0 || i % 5 === 0){
total += i;
}
}
return total;
}
- Final step: returning the total sum
function solution(number){
let total = 0;
if(number < 0){ return 0}
for(let i = 1; i < number; i++){
if(i % 3 === 0 || i % 5 === 0){
total += i;
}
}
return total; // This is where the sum gets returned
}
Top comments (0)