The array A [N] contains natural numbers. Find the sum of those elements that are multiples of a given K

Viewed 45

I would appreciate if you could help me find an error in my code. Sorry, I'm new as you can see.

var arr = prompt("Enter your numbers separating by comma").split(",");
arr = arr.map(Number);
var n = prompt("N");
let arr1;
var n = parseInt(n);
for (var i = 1; i < arr.length; i++) {
  if (arr.get(i) % n == 0) {
    function() {
      arr1 = arr.get(i);
    }
  }
}
console.log(arr1);

3 Answers

You don't have to create internal function within for loop:

let sum = 0;
for (var i = 0; i < arr.length; i++) {
  if (arr[i] % n === 0) {
      sum += arr[i];
  }
}

Or more JS-way:

const sum = arr.filter(e => e % n === 0).reduce((a, c) => a + c);

The function is not needed. You should just add the array element to a total variable.

Array elements are accessed as arr[i], not arr.get(i).

var arr = prompt("Enter your numbers separating by comma").split(",");
arr = arr.map(Number);
var n = prompt("N");
let total = 0;
var n = parseInt(n);
for (var i = 1; i < arr.length; i++) {
  if (arr[i] % n == 0) {
    total += arr[i];
  }
}
console.log(total);

that?

var arr = (prompt("Enter your numbers separating by comma").split(",")).map(Number)
  , n = parseInt( prompt("N") )
  ;
console.log( arr.reduce((r,v)=>r+(v%n?0:v),0) )

Related