Create a program that returns the smallest cube that exceeds a non-negative integer n

So, I'm trying to create a program that generates the smallest cube, different from the integer n.

def first_cube_above(n):
    #Return the smallest cube which exceeds the non-negative integer n.

    num = 1
    total = 0

    while total != 1:
        if pow(int(pow(n+num, 1/3)), 3) == n + num:
            total = 1
        else:
            num += 1

    print(n + num)

This seems to work for small integers, but I can't figure out why this doesn't work for others. Any help would be greatly appreciated.

+4
source share
2 answers

As @ martin.macko points out, you (erroneously) assume that pow(pow(x, 1/3), 3) == x. This is not due to floating point errors. In fact, performing a quick check, we find that there is (probably) only a small number of integers for which this is true:

good = [x for x in range(10**7) if pow(pow(x, 1/3), 3) == x]
good_cubes = [x**3 for x in range(1000) if pow(pow(x**3, 1/3), 3) == x**3]
# len(good) = 50

< <22 >

0, 1, 2, 6, 8, 9, 12, 16, 19, 23, 25, 27, 35, 44, 65, 66, 72, 73, 76, 83, 85, 91, 94, 96, 117, 127, 130, 139, 142, 147, 158, 170, 175, 513, 514, 520, 539, 547, 549, 551, 553, 562, 563, 576, 581, 601, 605, 663, 690, 699

good_cubes

0, 1, 8, 27

, 27, , . : next_cube = ceil(x**(1/3))**3 ceil - math.

0

. == . .

, 1, , n:

a = 1
while a ** 3 <= n:
    a += 1
print(a ** 3)

, O (n ^ (1/3)). , , , , , :

def cube(n):
    a = math.floor(pow(n, 1/3))
    while a ** 3 <= n:
        a += 1
    print(a ** 3)

. : cube(9085409385209438540928540295843025325) 9085409385221751364051702949589465608, 2086643068802

-1

Source: https://habr.com/ru/post/1662909/


All Articles