How can I golf this code to count all perfect squares below 100?
For the exact question posed: since we know that 1 is a perfect square and all integers between that and the maximal one (here 9) will be included we can simply find that maximal one:
print((100-1)**.5//1)
(//1
performing integer division by one to remove any fractional part may be replaced with /1
prior to Python 3.)
with both endpoints (an inclusive start
and exclusive stop
equivalent to a range
) this could be extended to a function (negative inputs catered for with max
):
f=lambda start, stop:print(max(0,stop-1)**.5//1-max(0,start)**.5//1)
For the record, below is another approach using additions and multiplications only.
The square of N is the sum of the N first odd positive integers:
1^2 = 1
2^2 = 1 + 3 = 4
3^2 = 1 + 3 + 5 = 9
4^2 = 1 + 3 + 5 + 7 = 16
etc.
Consequently, if we are to compute all perfect squares up to a given limit, each one can be quickly deduced from the previous one.
Hence the following possible algorithms:
# with 3 variables, using addition only
s = i = 1
n = 0
while s < 100:
n += 1
i += 2
s += i
print(n)
# with 2 variables, using addition and multiplication
s = 1
n = 0
while s < 100:
n += 1
s += n * 2 + 1
print(n)
Or as a recursive lambda:
f = lambda x, s=0, n=0: f(x, s+n*2+1, n+1) if s < x else n-1
print(f(100))