Javascript : Coding Challenge

  • Posted on March 23, 2024
  • JavaScript
  • By MmantraTech
  • 183 Views

Problem Statement :

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.

Also, if the number is negative, return 0.

 


 

Note: If the number is a multiple of both 3 and 5, only count it once.

References : codewars ,leetcode and others

 

Solution 1:

 

function solution(number) {
  var total = 0;

  if (number < 0) return 0;

  for (var i = 1; i < number; i++) {
    if (i % 3 == 0 || i % 5 == 0) {
      total += i;
    }
  }

  return total;
}

var n = 10;
var r = solution(n);
console.log(r);

Solution 2:

var n = 10;

 var result = [...Array(n).keys()];
 var after_filter = result.filter(x=>x%3==0 || x%5==0 );
 var total = after_filter.reduce((x,y)=>x+y);
 console.log("r==",total);

 

Solution 3:

var n=10;
var t =[...Array(n).keys()].filter(x=>x%3==0 || x%5==0 ).reduce((x,y)=>x+y)
console.log(t);
Author
No Image
Admin
MmantraTech

Mmantra Tech is a online platform that provides knowledge (in the form of blog and articles) into a wide range of subjects .

You May Also Like

Write a Response