Home > Net >  Find all triplets i,j,k such that i j k=n
Find all triplets i,j,k such that i j k=n

Time:01-25

I've coded this but this is very long:

for i in range(n   1):
    for j in range(n   1):
        for k in range(n   1):
            if i   j   k == n:

Is there a clever way to make it go faster? Currently it's O(n^3) which is quite sad.

CodePudding user response:

The innermost loop seems redundant since once you have i and j, k comes for free:

out = []
for i in range(n   1):
    for j in range(n   1):
        if i j <= n:
            print((i, j, n-i-j))

CodePudding user response:

There are few ways to make the code run faster.

  1. Use a list comprehension. Syntax [ReturnThing ForLoops Condition]

  2. Start each loop from where the previous loop got to. This avoid duplicates

    def MakeTriplet(n):                                                                          
        return [(i,j,k) for i in range(0,n 1) for j in range(i,n 1) for k in range(j,n 1) if (i j k)==n]
    

CodePudding user response:

The idea in enke's answer is correct, but implementation could be better. Here is a bit optimized code:

for i in range(1, n   1):
    for j in range(i, n   1):
        k = n - i - j
        if j < k:
            print(i, j, k)
        else:
            break

It will print all unique triplets.

  •  Tags:  
  • Related