1
 var number = prompt('Input a number!');
 var n = number;
   function getList() {


 for (var n = 1; n <= 17; n++) {


   if (n % 3 == 0 || n % 5 == 0) 
     console.log (n);
   }
 }


console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!

Ken
  • 13
  • 4

5 Answers5

1

var sum = 0;
for (var n = 1; n <= 17; n++) {
   if (n % 3 === 0 || n % 5 === 0) 
     sum += n;
}

console.log(sum);
Nima Hakimi
  • 1,382
  • 1
  • 8
  • 23
1

Use a variable to add the numbers and return it after for loop.

Below it the exapmle.

function getList() {
  var sum = 0;

  for (var n = 1; n <= 17; n++) {
    if (n % 3 == 0 || n % 5 == 0) {
      sum += n;
    }
  }
  
  return sum;
}


console.log(getList());
Shubham
  • 1,755
  • 3
  • 17
  • 33
  • 1
    This is by far the best solution, as the OP asked *How to return the sum*. Then, use the `return` statement. – Den Isahac Jul 06 '17 at 07:34
0

If you want an equation :)

function sumOfNumbersDivisibleBy3Or5(n) {
   const by3 = Math.floor(n/3),
         by5 = Math.floor(n/5),
         by3And5 = Math.floor(n/3/5);

  return 3*by3*(by3+1)/2 + 5*by5*(by5 + 1)/2 - 3*5*by3And5*(by3And5 + 1)/2
}

console.log(sumOfNumbersDivisibleBy3Or5(17))
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
0

Two things:

  1. Just return the sum from your getList function

  2. Make sure your prompt input is converted to integer otherwise it will be treated as a string and your n*(n+1)/2 will be wrong

var number = parseInt(prompt('Input a number!'));
var n = number;

function getList() {
  var sum = 0;
  
  for (var n = 1; n <= 17; n++) {
    if (n % 3 == 0 || n % 5 == 0) {
      console.log (n);
      sum += n;
    }
  }
  
  return sum;
}


console.log(getList());
console.log(n, (n*(n+1))/2);
Ivan Sivak
  • 7,178
  • 3
  • 36
  • 42
0

var number = prompt('Input a number!');
 function getList() {
  var sum = 0;
  for (var n = 1; n <= number; n++) {
   if (n % 3 == 0 || n % 5 == 0) 
     sum+=n;
   }
  return sum;
 }
console.log(getList());

it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number

Durga
  • 15,263
  • 2
  • 28
  • 52