This amazing code golf answer to Is this number Loeschian? in its entirety:
Python, 49 bytes
lambda n:0in[(n-3*i*i+0j)**.5%1for i in range(n)]
Uses the equivalent quadratic form given on OEIS of
n == 3*i*i+j*j
. Check whethern-3*i*i
is a perfect square for anyi
by taking its square root and checking if it's an integer, i.e. equals 0 modulo 1. Note that Python computes square roots of perfect squares exactly, without floating point error. The+0j
makes it a complex number to avoid an error on the square root of a negative.
How does Python do this? Does **.5
"detect" that a given number is a perfect square somehow? Is this only reliable for integer input or will it work on floats up to some size as well?
I've also added a parenthetical Why? to the question; is this something that programmers rely upon? Is it for speed? Does it come with a cost?