[Python] my code is giving me the wrong output sometimes, how to solve it? [closed]

Discussão em 'Python' iniciado por Stack, Junho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to solve this problem:


    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 n^3, the cube above will have the volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

    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 n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.
    ​

    I tried to first create an arithmetic sequence then transform it into a sigma sum with the nth term of the arithmetic sequence, then get a formula which I can compare its value with m.

    I used this code and it works 70 - 80% fine; most of the calculations that it does are correct, but some aren't.

    import math

    def find_nb(m):
    n = 0
    while n < 100000:
    if math.pow(math.pow(n, 2)+n, 2) == 4*m:
    return n
    break
    n += 1
    return -1

    print(find_nb(4183059834009))
    # output 2022, which is correct
    print(find_nb(24723578342962))
    # output -1, which is also correct
    print(find_nb(4837083252765022010))
    # output -1, which is incorrect
    # expected output 57323

    Continue reading...

Compartilhe esta Página