algorithmpython-3.xbrute-forcecubes

Generate all cubes with a given volume


I need to generate all possible (a, b, c) such as, a * b * c = V, where V is function parameter.

Is there some right way to complete my task? I try use full brute-force by a, b, c, but It is very slow. It is due to the fact, that V may be more than 10^4.

P.S. a, b, c is integer numbers.


Solution

  • I'm guessing you're doing something like this:

    def prisms(V):
        for a in range(1, V+1):
            for b in range(1, V+1):
                for c in range(1, V+1):
                    if a*b*c = V:
                        print a,b,c
    

    You can reduce the complexity from O(N^3) to O(N^2) by deriving the value of C from the already-known values of A and B.

    def prisms(V):
        for a in range(1, V+1):
            for b in range(1, V+1):
                if V % (a*b) == 0:
                    c = V / (a*b)
                    print a,b,c
    

    This isn't the most efficient way to do it, but it's simple and may be good enough for values of V around 10**4.