Home > other >  Problem with the output of a for...loop - JavaScript
Problem with the output of a for...loop - JavaScript

Time:11-15

I'm working through a JavaScript challenge problem Find Numbers with the Same Amount of Divisors and have run into some trouble at the end of my code where a for loop is involved.

The problem:

Find all pairs of numbers between 1 and NMax that are diff numbers apart and share the same amount of divisors.

For example: For numbers between 1 and 50, there are 8 numbers share the same number of divisors: [[2,3], [14,15], [21,22], [26,27], [33, 34], [34, 35], [38, 39], [44, 45]]

In my code below, count_pairsInt(1,50) will return 8, but count_pairsInt (3,100) returns TypeError: Cannot read properties of undefined (reading '1').

I'm almost certain something has gone awry in the last for loop, but I can't quite get my mind around what it is. Could someone help me out?

function countPairsInt(diff, nMax) {
  const numbers = [];
  for (let i=1; i<=nMax; i  ) {
    numbers.push(i);
  }
 
// divisors loops over each number passed in and returns the number of divisors for that number
  function divisors(num) {
    let divs = [];
    for (let i=1; i<=num; i  ) {
    if (num % i === 0) divs.push(i);
    }
    return divs;
  }
  
// create an array of arrays, each subarray contains the number and it's number of divisors by passing map over the numbers array.
  const numsAndDivs = numbers.map(x=> [x, divisors(x).length]);
  let equalDivs = 0;
  for (let i=1; i<numsAndDivs.length-1; i  ) { 
    if (numsAndDivs[i][1] === numsAndDivs[i diff][1] ){
      equalDivs  ;
    }
  }
  return equalDivs
}


countPairsInt(1, 50); // returns 8
countPairsInt(3, 100) // should return 7

CodePudding user response:

You forgot to add a simple check that i diff must be less than numsAndDivs.length. it was getting 100 in your case and there was no array of index 100 in numsAndDivs. hence the error.

if (i  diff < numsAndDivs.length && numsAndDivs[i][1] === numsAndDivs[i diff][1] ){
        equalDivs  ;
 }
  • Related