5
\$\begingroup\$

The problem is to find out the squares between two numbers, inclusive of the numbers. The two numbers are in the range between 1 and 109.

long numberOne = in.nextLong();
 long numberTwo = in.nextLong();
 int count=0;
 for(long j=numberOne;j<=numberTwo;j++){
 double numSquareRoot=Math.sqrt(j);
 double numFloor=Math.floor(numSquareRoot);
 if(numSquareRoot == numFloor) count++;
 }

What changes can be made to work efficiently on large numbers?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 10, 2015 at 3:45
\$\endgroup\$

1 Answer 1

12
\$\begingroup\$

Can be done in \$O(1)\$ time

The count should be:

\$\lfloor{\sqrt n}\rfloor -\lceil{\sqrt m}\rceil + 1\$

or in terms of your program:

return Math.floor(Math.sqrt(numberTwo)) - Math.ceil(Math.sqrt(numberOne)) + 1;
answered Oct 10, 2015 at 4:21
\$\endgroup\$
1
  • \$\begingroup\$ I'm not math background. Mind to explain as simple as you could how you get this? And whats that O(1) time? What topic/subject is that? \$\endgroup\$ Commented Jun 3, 2016 at 0:18

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.