Home > Software engineering >  Finding the square root of numbers in a range in JavaScript without using Math.sqrt() and Only For L
Finding the square root of numbers in a range in JavaScript without using Math.sqrt() and Only For L

Time:01-29

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for(let i = 0; i < max; i  ) {
    arrNum.push(i);
  }
  return arrNum;
}

Can Only use JavaScript and for loops or for of or for in along with if else.

This pushes the numbers 0 through 200 into my empty array. What I need my code to do is go through the array and get every number that can be a square root. For example: if Max = 200, every number in the range of 0 to 200 find each number that have square roots that are integers. The array would return [0, 1, 4, 9, 16 etc..., till 196 because anything after this is not a square root]. I know that 2 ** 2 is possible for finding square roots.

I have tried even using Math.sqrt() But I end up with just an array of numbers being squared.

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for (let i = 0; i < max; i  ) {
    arrNum.push(Math.sqrt(i));
  }
  return arrNum;
}

CodePudding user response:

You can square each number and check to see if the result is less than the maximum.

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for (let i = 0; i < max; i  ) {
    var square = i * i;
    if (square < max) {
        arrNum.push(square);
    }
    else {
        break;
    }
  }
  return arrNum;
}

The else is only there to break out of the loop once you've gone beyond the maximum.

CodePudding user response:

This pushes the numbers 0 through 200 into my empty array. What I need my code to do is go through the array and get every number that can be a square root.

No, that's the wrong approach. Don't go through 200 numbers and try to find out which of them is square (has an integer square root). Instead, loop and put only square numbers in the array in the first place! That is much simpler and more efficient.

CodePudding user response:

You can even do it without an if and without any multiplication:

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for (let sq=i=0; (sq =i i 1) < max; i  ) arrNum.push(sq);
  return arrNum;
}

console.log(getNumbersWithSquareRoots(200))

CodePudding user response:

function getNumbersWithSquareRoots(max) {
  const arrNum = [];
  for (let i = 0; i < max; i  ) {
    var square = i * i;
    if (square < max) {
       arrNum.push(square);
   }
  }
return arrNum;
}

This ended up working for my task that I was trying to complete. Thank you everyone.

  • Related