Python Exercise Example 3
**Problem:** An integer, when increased by 100 becomes a perfect square, and when increased by another 168 becomes a perfect square again. What is this number?
Program analysis:
Assume the number is x.
1. Then: x + 100 = n2, x + 100 + 168 = m2
2. Compute 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
4. We get: m = (i + j) / 2, n = (i - j) / 2; i and j are either both even or both odd.
5. From 3 and 4 we can deduce that both i and j are even numbers greater than or equal to 2.
6. Since i * j = 168 and j >= 2, then 1 < i < 168 / 2 + 1.
7. Next, just loop through all possible values of i to compute.
Program source code:
Example (Python 3.0+)
Define the solving function
def
find_integer
(
)
:
for
i
in
range
(
2
,
85
)
:
i ranges from 2 to 84
if
168
% i
==
0
:
i is a factor of 168
j
=
168
// i
Calculate the corresponding j
if
i
j
and
(
i + j
)
%
2
==
0
and
(
i - j
)
%
2
==
0
:
Ensure that i and j are both even or both odd
m
=
(
i + j
)
//
2
n
=
(
i - j
)
//
2
x
=
n * n -
100
(
f
"x: {x}, m: {m}, n: {n}"
)
Call the solving function
find_integer
(
)
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
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
(
x
)
The output of the above example is:
-99
21
261
1581
Python 100 Examples