0

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
2
  • What did you discover when you used your debugger to step through the code? Commented Nov 14, 2022 at 20:02
  • I'll admit that debugging is a skill that I'm not very proficient with, I usually write and test programs with RunJS, but it wasn't returning results that I could use to figure out what was going on. I just run the code through the browser's console and go the following: Uncaught TypeError: numsAndDivs[(i + diff)] is undefined which is more helpful. Is the best way to debug to use Chrome/Firefox's debugger? Commented Nov 14, 2022 at 22:01

1 Answer 1

1

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++;
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.