I need to write a program that finds all perfect squares between two given numbers a and b such that the range can also be a = 1 and b = 10^15 what is the best way I can do this, how do I list down all such square numbers, is there some abstract math hidden underneath this problem?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
One thing that makes this pretty straight forward is this: $(n+1)^2-n^2=2n+1$ Start with one, and keep on adding that.
You can do it much easily by first calculating the square roots of $a$ and $b$. And count the number of integers between those square roots (just subtract one from the other). But be careful when one of $a$ and $b$ is a square itself.
Here's some code (pretty much C/C++) to implement Chris Dugale's answer:
The idea is that $(n+1)^2=n^2+2n+1$, so to get $(n+1)^2$ from $n^2$, just add $2n+1$ to it. Then, to get $(n+2)^2$ from $(n+1)^2$ you add $2n+3$, and so on...
protected by Zev Chonoles Sep 23 '15 at 19:31
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?