我刚开始编程1周前所以请原谅你将要看到的混乱 我试图找到第一个x出租车号码,但我的“嵌套for循环”程序需要很长时间才能完成所有可能性。 出租车号码: 如果有一个数字a ^ 3 + b ^ 3等于c ^ 3 + d ^ 3 这笔钱是一个taxinumber。例 12 ^ 3 + 1 ^ 3 == 10 ^ 3 + 9 ^ 3 == 1729
对我来说,如果我能找到大约20个taxinumber,它就会成功 预先感谢任何提示或技巧!
这是我的代码:
import math
def main():
numbersOfResultsToFind = getNumberOfTaxisToFind()
foundResults = 0
numberToCheck = 1
while(foundResults < numbersOfResultsToFind):
result = getTaxi(numberToCheck)
if len(result) > 1: #if more then one a+b
foundResults = foundResults + 1
print(numberToCheck, result)
numberToCheck = numberToCheck + 1
def getNumberOfTaxisToFind():
return int(input("How many taxinumbers do you want to find? "))
def getThirdSquareFloored(value):
value = value**(1/3)
value = math.floor(value) #floor value
return value
def getTaxi(numberToCheck):
result = []
upperLimit = getThirdSquareFloored(numberToCheck)
for a in range(1, upperLimit+1):
for b in range(1, upperLimit+1):
aCubed = a**3
bCubed = b**3
sumCub = aCubed + bCubed
if(sumCub == numberToCheck and a < b):
result.append((a, b))
return result
main()
答案 0 :(得分:0)
问题在于Taxicab numbers非常远。你可以做一些数学技巧来解决它。例如,您可以检查Euler's sum of powers。这种方法的问题在于你将产生一些出租车号码,但它们可能不合适。
在你的代码中,我有一些注意事项:
value**(1/3)
!请记住python中的1/3 = 0
。使用1./3
或使用numpy
**(1./3)
- 任何电源功能都很昂贵,尝试用某些东西替换它们(预先计算好的值?)答案 1 :(得分:0)
import math
def main():
numbersOfResultsToFind = getNumberOfTaxisToFind()
foundResults = 0
numberToCheck = 1
while(foundResults < numbersOfResultsToFind):
result = getTaxi(numberToCheck)
if len(result) > 1:
foundResults = foundResults + 1
print(numberToCheck, result)
numberToCheck = numberToCheck + 1
def getNumberOfTaxisToFind():
return int(input("How many taxinumbers do you want to find? "))
def getThirdSquareFloored(value):
value = value**(1./3)
value = math.floor(value)
return value
def getTaxi(numberToCheck):
result = []
upperLimit = getThirdSquareFloored(numberToCheck)
for a in range(1, upperLimit+1):
b = round((numberToCheck-a**3)**(1./3))
if(a**3+b**3 == numberToCheck and a < b):
result.append((a, b))
if len(result) == 2:
break
return result
main()
非常感谢大家的帮助!这是我更新的代码,运行速度更快。我设置b值是从a而不是使用嵌套for循环计算的。我还实现了一个if len(结果),在我的代码结尾处中断 如果已找到配对,没有理由继续寻找配对