Find the a 4 digit number who's square is 8 digits AND last 4 digits are the original number
Here is a 1-liner solution without any modules:
>>> next((x for x in range(1000, 10000) if str(x*x)[-4:] == str(x)), None)
9376
If you consider numbers from 1000
to 3162
, their square gives you a 7
digit number. So iterating from 3163
would be a more optimized because the square should be a 8
digit one. Thanks to @adrin for such a good point.
>>> next((x for x in range(3163, 10000) if str(x*x)[-4:] == str(x)), None)
9376
If you are happy with using a 3rd party library, you can use numpy
. This version combines with numba
for optimization.
import numpy as np
from numba import jit
@jit(nopython=True)
def find_result():
for x in range(1e7**0.5, 1e9**0.5):
i = x**2
if i % 1e4 == x:
return (x, i)
print(find_result())
# (9376, 87909376)
[Almost] 1-liner:
from math import sqrt, ceil, floor
print(next(x for x in range(ceil(sqrt(10 ** 7)), floor(sqrt(10 ** 8 - 1))) if x == (x * x) % 10000))
printing:
9376
Timing:
%timeit next(x for x in range(ceil(sqrt(10 ** 7)), floor(sqrt(10 ** 8 - 1))) if x == (x * x) % 10000)
546 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
@theausome 's answer (the shortest (character-wise)):
%timeit next((x for x in range(3163, 10000) if str(x*x)[-4:] == str(x)), None)
3.09 ms ± 119 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
@jpp 's answer (the fastest):
import numpy as np
from numba import jit
@jit(nopython=True)
def find_result():
for x in range(1e7**0.5, 1e9**0.5):
i = x**2
if i % 1e4 == x:
return (x, i)
%timeit find_result()
61.8 µs ± 1.46 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)