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(i**3 j**3 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
CodePudding user response:
The nested loops are not your problem, they are already correct.
You need to print the values of i
, j
, k
, and N
only if they satisfy the equation. For this purpose of conditional execution of code, Python (as many other programming languages) has if
statements.
You learn about them in the official Python tutorial or in any good beginners book about programming in Python, like Think Python or Automate the Boring Stuff with Python.
In your case, you can apply an if
statement like this:
Instead of unconditionally printing
print(i**3 j**3 k**3==N,end=" ")
use
if i**3 j**3 k**3==N:
print(i, j, k, N)
CodePudding user response:
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
CodePudding user response:
This will give you the number of times the equation is correct:
count = 0
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:
count = 1
print(count)