[SOLVED] Nested for loop python equation

Issue

This Content is from Stack Overflow. Question asked by Brandon Letendre

I am new to python and coding and I have a problem where I need to use nested for loops to solve an equation where i^3 + j^3 + k^3 = N. Where N is 50 to 53 and i,j,k have a range of -800 to 800.

I do not understand how to use a nested for loop for this. Every example I have seen of for loops they are used for creating matrices or arrays.

The code I have tried output a very large amounts of falses.

for i in range (-800,801):
for j in range (-800,801):
for k in range(-800,801):
for N in range (50,54):
print(i3+j3+k**3==N,end=” “)
print()

Am I on the right track here? I got a large amount of false outputs so does that mean it ran it and is giving me a every possible outcome? I just need to know the numbers that exists that make the statement true



Solution

I think what you want to do is check if
i^3+j^3+k^3==N
and only print i, j and k if the statement is true.

You can do that by adding:

for i in range(-800, 801):
    for j in range(-800, 801):
        for k in range(-800, 801):
            for N in range(50, 54):
                if i**3+j**3+k**3 == N:
                    print(i, j, k, N)

output:

-796 602 659 51
-796 659 602 51


This Question was asked in StackOverflow by Brandon Letendre and Answered by bitflip It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?