uj5u.com熱心網友回復:
#x和y 都是整數 求出x和y的所有可能# x + y = A
# x * y = B
def fun(A,B):
for i in range(A):
for j in range(B):
if i + j == A and i * j == B:
print(i,j)
fun(8,15)
for 回圈嵌套 可以求出這個解
uj5u.com熱心網友回復:
這個題用回圈可能不行,因為 A、B是整數,包括正整數、零、負整數比如: A = 7, B = -120,
解是:
X = 15, Y = -8
X = -8, Y = 15
解方程吧:
x^2 - Ax + B = 0
// pseudocode:
delta = A^2 - 4B
if delta < 0 then 'No solution'
else
if SQRT(delta) is not integer AND (A + SQRT(delta) % 2 is not integer AND (A - SQRT(delta) % 2 is not integer
then 'No Solution'
else
X1 = (A + SQRT( A^2 - 4B) )/ 2 , X2 = (A - SQRT( A^2 - 4B) ) / 2
if X1 == X2 then only one solution: X = X1, Y = X1
else there are two distinct solutions:
X = X1, Y = X2 and X = X2, Y = X1
注意 根的取整 (123.0 變成 123)
uj5u.com熱心網友回復:
please input A(integer,|A|<1e7):-1please input B(integer,|B|<1e14):-12
X = 3, Y = -4
X = -4, Y = 3
A = (int)(input("please input A(integer,|A|<1e7):"))
B = (int)(input("please input B(integer,|B|<1e14):"))
if (abs(A) >= 1e7 or abs(B) >= 1e14) :
print("Invaild inputs")
def func(A , B) :
threshold = (A) * (A) - 2 * (B) + 1
for i in range(threshold) :
for j in range(threshold) :
if (i + j == A and i * j == B) :
print("X = {}, Y = {}".format(i , j))
print("X = {}, Y = {}".format(j , i))
return
elif (-i + j == A and -i * j == B) :
print("X = {}, Y = {}".format(-i , j))
print("X = {}, Y = {}".format(j , -i))
return
elif (-i - j == A and i * j == B) :
print("X = {}, Y = {}".format(-i , -j))
print("X = {}, Y = {}".format(-j , -i))
return
elif (i - j == A and -i * j == B) :
print("X = {}, Y = {}".format(i , -j))
print("X = {}, Y = {}".format(-j , i))
return
return -1
if func(A , B) == -1 :
print("No solution")
uj5u.com熱心網友回復:
判定一個數是否是整數,內建的函式 is_integer() 比較有用:a = 1.2
a.is_integer() # False
b = 1.0
b.is_integer() # True
uj5u.com熱心網友回復:
判定那里有點問題,是 “/” 不是 “% ”:
if SQRT(delta) is not integer AND (A + SQRT(delta) / 2 is not integer AND (A - SQRT(delta) / 2 is not integer
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/167099.html
