Interview question: An integer is a perfect square when added to 100, and 168 is a perfect square. What is the number?




For math problems like this, we don’t need to write code, we need to analyze the calculation logic first:


Let’s say that this number is x.


1, then: x + 100 = n2, x + 100 + 168 = m2


2, calculate the equation: m2 – n2 = (m + n)(m-n) = 168


3, set: m + n = I, m-n = j, I * j =168, at least one of I and j is even


M = (I + j) / 2, n = (i-j) / 2, I and j are either even or odd.


5. It can be inferred from 3 and 4 that I and j are both even integers greater than or equal to 2.


6, if I * j = 168 and j>=2, then 1 < I < 168/2 + 1.


7. Then loop all the digits of I.


After the logic is analyzed, the code is easy to implement:


[Python]

Plain text view
Copy the code

?
01
02
03
04
05
06
07
08
09
10
11
12
13
def
main():

for
i
in
range
(
1
.
85
) :

if
168
%
i
=
=
0
:

j
=
168
/
/
i

if
i > j
and
(i
+
j)
%
2
=
=
0
and
(i
-
j)
%
2
=
=
0
:

m
=
(i
+
j)
/
/
2

n
=
(i
-
j)
/
/
2

x
=
n
*
n
-
100

print
(x)
if
__name__
=
=
'__main__'
:

main()


For more technical advice: Gzitcast