Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the a 4 digit number who's square is 8 digits AND last 4 digits are the original number [closed]

From the comments on my answer here, the question was asked (paraphrase):

Write a Python program to find a 4 digit whole number, that when multiplied to itself, you get an 8 digit whole number whose last 4 digits are equal to the original number.

I will post my answer, but am interested in a more elegant solutions concise but easily readable solution! (Would someone new-ish to python be able to understand it?)

like image 690
Aaron N. Brock Avatar asked Apr 05 '18 12:04

Aaron N. Brock


1 Answers

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
like image 127
Austin Avatar answered Nov 15 '22 23:11

Austin