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?
2026-04-01 19:13:35.1775070815
On
How to find all perfect squares in a given range of numbers?
70.2k Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail At
2
There are 2 best solutions below
4
On
Here's some code (pretty much C/C++) to implement Chris Dugale's answer:
long i = 1;
for (long n = i*i; i < k; i++) {
n += 2i + 1;
printf("%l\n", n);
}
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...
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.