英文:
Codewars challenge solution is too slow
问题
你可以尝试使用数学方法来加速解决这个问题。这是一个求等差数列和的问题,你可以使用以下公式来计算:
n^3 + (n-1)^3 + (n-2)^3 + ... + 1^3 = (n * (n + 1) / 2)^2
你可以将这个公式用于给定的 m,然后解出 n。如果解存在,返回 n;否则返回 -1。
以下是修改后的代码:
import math
def find_nb(m):
n = int(math.sqrt(math.sqrt(2 * math.sqrt(m)))
if (n * (n + 1) / 2) ** 2 == m:
return n
else:
return -1
print(find_nb(135440716410000))
这个方法应该比你之前的循环更快,因为它直接计算了结果而不需要遍历。
英文:
The challenge is like so:
Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n3 n^3 n3, the cube above will have volume of (n−1)3 (n-1)^3 (n−1)3 and so on until the top which will have a volume of 13 1^3 13.
You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
The parameter of the function findNb (find_nb, find-nb, findNb, ...) will be an integer m and you have to return the integer n such as n3+(n−1)3+(n−2)3+...+13=m n^3 + (n-1)^3 + (n-2)^3 + ... + 1^3 = m n3+(n−1)3+(n−2)3+...+13=m if such a n exists or -1 if there is no such n.
Examples:
findNb(1071225) --> 45
findNb(91716553919377) --> -1
I have solved as follows, but its too slow. Is there a way to make it faster?
def find_nb(m):
n = 0
x = 0
while x < m:
n += 1
x = sum([(n-i)**3 for i in range(n)])
if x == m:
return n
else:
continue
return -1
print(find_nb(135440716410000))
答案1
得分: -1
def findNb(m):
n = 0
while m > 0:
n += 1
m -= n**3
return n if m == 0 else -1
英文:
You can use this by python:
def findNb(m):
n = 0
while m &gt; 0:
n += 1
m -= n**3
return n if m == 0 else -1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论