Python Practice Example 3
Topic:An integer, after adding 100, is a perfect square, and after adding another 168, it is again a perfect square. What is the number?
Program analysis:
Assume the 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, and at least one of i and j is even.
4. It can be obtained: m = (i + j) / 2, n = (i - j) / 2, and i and j are either both even or both odd.
5. From 3 and 4, it can be deduced that i and j are both even numbers greater than or equal to 2.
6. Since i * j = 168, j >= 2, then1 < i < 168 / 2 + 1。
7. Next, loop through all values of i and calculate.
Program source code:
Example (Python 3.0+)
# Define the solving function
def find_integer():
for i in range(2, 85): # The range of i is 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 i and j are both even or both odd
m = (i + j) // 2
n = (i - j) // 2
x = n * n - 100
print(f"x: {x}, m: {m}, n: {n}")
# Call the solving function
find_integer()
def find_integer():
for i in range(2, 85): # The range of i is 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 i and j are both even or both odd
m = (i + j) // 2
n = (i - j) // 2
x = n * n - 100
print(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
print(x)
# -*- 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
print(x)
The output of the above example is:
-99 21 261 1581Other Extensions
Python 100 Examples