Home > Software engineering >  splice method in nested loop is removing unintenionally numbers
splice method in nested loop is removing unintenionally numbers

Time:11-27

I want to find all prime numbers in a certain range. I do this with looping through the array with numbers. If a multiplier of the current number is found, then it will be removed from the array with the splice method. But some numbers will be removed like 7 and 11 which are actually prime number and some not like 8 which are not prime numbers. What is wrong in this program, I can not figure it out.

let list = [];
for (let i = 2; i <= 30; i  ) {
  list.push(i);
}

let n = list.length - 1;

for (let prim = 0; prim <= n; prim  ) {
  //multiplier is beginning at 1 for provide 2 from splice method
  for (let multiplier = 0; multiplier <= n; multiplier  ) {
    //if the currentNumber is divisible by "prim" then remove it from list

    if (list[multiplier] % list[prim] == 0) {
      list.splice(multiplier, 1);
    }
  }
}

console.log(list);

CodePudding user response:

Splicing with deleting changes the index for the following elements.

To avoid this, you need to iterate from the end. By doing so, you need not to iterate over the index of the prime number, you are checking.

let list = [];
for (let i = 2; i <= 30; i  ) list.push(i);

for (let prim = 0; prim < list.length - 1; prim  ) {
    for (let multiplier = list.length - 1; multiplier > prim; multiplier--) {
        if (list[multiplier] % list[prim] == 0) list.splice(multiplier, 1);
    }
    console.log(...list)
}

console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

splice removes the element from the list which changes the size of your list you didn't check the condition for if list[multiplier] and list[prim] are the same numbers

let list = [];
for (let i = 2; i <= 30; i  ) {
  list.push(i);
}

for (let prim = 0; prim <list.length-1; prim  ) {
  for (let multiplier = prim; multiplier <list.length; multiplier  ) {
    if (list[multiplier] != list[prim] && list[multiplier] % list[prim] == 0) {
      list.splice(multiplier, 1);
    }
  }
}

console.log(list);

  • Related