[英]why is my code producing one more than it should?
I am trying to solve the following problem: Your task is to construct a building which will be a pile of n cubes.我正在尝试解决以下问题:您的任务是建造一座由 n 个立方体组成的建筑物。 The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
底部的立方体的体积为 n^3,上面的立方体的体积为 (n-1)^3,依此类推,直到顶部的体积为 1^3。
You are given the total volume m of the building.给定建筑物的总体积 m。 Being given m can you find the number n of cubes you will have to build?
给定 m 你能找到你必须建造的立方体的数量 n 吗?
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 n^3 + (n-1)^3 +... + 1^3 = m
if such an exists or -1 if there is no such n. 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
n^3 + (n-1)^3 +... + 1^3 = m
如果存在这样的一个,则为n^3 + (n-1)^3 +... + 1^3 = m
,如果不存在这样的 n,则为 -1。
Examples:例子:
findNb(1071225) --> 45
findNb(91716553919377) --> -1
Here is my code:这是我的代码:
def find_Nb(m):
n = 1
while n <= m // 2:
total_n = 0
for i in range(0, n):
total_n += (n - i) ** 3
n += 1
if total_n == m:
return n
break
else:
return -1
For some reason, the output produces (n+1) in the case where total_n ==m.出于某种原因,output 在 total_n ==m 的情况下产生 (n+1)。 So for example, if we do m = 100, the output should be 4;
例如,如果我们做 m = 100,那么 output 应该是 4; but the above code produces 5;
但上面的代码产生 5; any idea why this is?
知道这是为什么吗?
Or as per the example, when I run m=1071225 into the code I should get an output of 45, but my code produces 46.或者根据示例,当我在代码中运行 m=1071225 时,我应该得到 45 的 output,但我的代码产生 46。
this is the code that I wrote and it works but when I first tried it I had the same problem as you.这是我编写的代码,它可以工作,但是当我第一次尝试它时,我遇到了和你一样的问题。 I fixed it by putting the n = i before i+=1 so that n has the right value so I think you too have to make a copy of n before you say n += 1 and to return that value.
我通过将 n = i 放在 i+=1 之前来修复它,以便 n 具有正确的值,所以我认为您也必须在说 n += 1 之前复制 n 并返回该值。
def findN(m):
sum = 0
i = 1
while sum < m:
sum += i ** 3
n = i
i += 1
if sum == m:
return n
else:
return -1
print(findN(1071225))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.