3
\$\begingroup\$

The function below passes most test cases:

function numOfSquares(a, b) { 
 const isSquare = function (n) {
 return n > 0 && Math.sqrt(n) % 1 === 0;
 };
 let squareCount = 0;
 for (let i = a; i <= b; i++){
 if (isSquare(i)) {
 squareCount++;
 }
 }
 return squareCount
}

numOfSquares(3, 9) //out: 2 numOfSquares(17, 24) //out: 0

The time complexity of this is O(n)... right?

The problem is that this function does not pass the test cases being provided due to the time complexity. For example, in one case, the input could be numOfSquares(465868129, 988379794) (expected out: 9855). In my case, using the function above, it seems to run... forever.

How can I make this function more efficient, and thus faster?

asked Aug 30, 2020 at 22:25
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

You are correct that your solution is O(n). However, there is a possible solution for O(1). If you find the root of the first square (first) and the last square (last), then all of the numbers between first and last will yield squares in the range.

function numSquares(min,max) {
 const first = Math.ceil(Math.sqrt(min));
 const last = Math.floor(Math.sqrt(max));
 return last-first+1;
}
console.log(numSquares(465868129, 988379794));
answered Aug 31, 2020 at 1:31
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.