javascriptequations

javascript - functions and equations confusion


 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!


Solution

  • 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);