DEV Community

Cover image for Codewars: Multiples of 3 or 5
CLeeBenjamin
CLeeBenjamin

Posted on

1

Codewars: Multiples of 3 or 5

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)
Enter fullscreen mode Exit fullscreen mode

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}
}
Enter fullscreen mode Exit fullscreen mode

- 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; 
}
Enter fullscreen mode Exit fullscreen mode

- 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
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay