題干:
撰寫一個程式,對于任意給定的正整數 N(N<=100),尋找所有的四元組(a,b,c,d),滿足 a**3 = b**3 + c**3 + d**3
其中 1 < a,b,c,d <=N。按照 a 的值從小到大,每行輸出一個完美立方等式,其中b,c,d按照非降序排列輸出。????????????????????????????????????????????????????????????????????????????????????????????????
(若兩個完美立方式中 a 值相同,則 b 值小的先輸出;在 b 值相等的情況下,c 值小的先輸出,在 b,c 都相等的情況下,d 值小的先輸出)
答案:
import itertools
n = int(input())
ls = list(itertools.combinations(range(2,n+1),3))
ln=[]
for i in ls:
s = sum(x**3 for x in i)
if round(s**(1/3),3)==int(round(s**(1/3),3))<=n:
ln=ln+[(int(round(s**(1/3),3)),i)]
ln.sort(key=(lambda x: x[0]))
for i in ln:
print("Cube = {},Triple = {}".format(i[0], i[1]))
uj5u.com熱心網友回復:
import itertools
n = int(input())
ls = list(itertools.combinations(range(2,n+1),3))
ln=[]
for i in ls:
s = sum(x**3 for x in i)
if round(s**(1/3),3)==int(round(s**(1/3),3))<=n:
ln=ln+[(int(round(s**(1/3),3)),i)]
ln.sort(key=(lambda x: x[0]))
for i in ln:
print("Cube = {},Triple = {}".format(i[0], i[1]))
round(number[, ndigits])
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.
class int(x, base=10)
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
uj5u.com熱心網友回復:
Thanks for your reply and explain!However,which I truly cannot understand is its content not the function .So I still in puzzle...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/256913.html
下一篇:有問題尋求大佬幫助
