

If that occurs, then the number has a divisor other than 1 and the number itself and the number isn’t a prime number. The most naive and straightforward implementation is to loop over the range of numbers from 2 to the number and see if the modulo of the number and the range is equal to 0. Let’s take a look at how we can use Python to determine if a number is a prime number. Finding Prime Numbers in Python (Optimized Code)

The first few prime numbers are: 3, 7, 11, 13, etc. For example, the number 5 is a prime number, while the number 6 isn’t (since 2 x 3 is equal to 6). Prime numbers are a positive integer that’s greater than 1 that also have no other factors except for 1 and the number itself.

If you have any other questions, please feel free to ask. This seems a little odd, for it would be more clerical if it said: if (i%j = 0): The only thing that is weird about this code, in my opinion is the: if not (i%j) This means that j is never going to start out to be two, even though we are adding to j in the SECOND (NESTED) while loop.Įverything from here should make sense, if I understood your question right. Not only is it equal to 2, but every time we go down to the bottom of this FIRST WHILE LOOP THAT ENDS WHEN i >=50, we go back to the start and reinitialize j to be 2 again. This variable is equal to 2, as we can see. So, now we are inside of the first while loop, and the next thing we are doing is calling j. We are then initializing a while loop that is going to stop when i is greater than 50. The first to realize is that we are starting off with i=2. Now, let us approach what is going on inside of this code. The second thing that we are able to do is see what is being incremented where. The first thing we are able to do is get a nice visual of what is inside of what, instead of assuming anything. i = 2īy writing the code like this, we are able to do several things. Did I miss any increments here? Thank you.įirst of all, I would like to post the correct syntax for the code. And I want to know what part I did wrong here.

But (3 <= (6/3)) <- this is not true, so it goes to if statement and 3 which is j is bigger than 2 which is i/j, which means 6 should be prime.īut it's not. So j should still be 3 and i should be 6. So j should be 3 and i should be 5, 5 is prime, then it increments again to 6. Then it's not a prime number, so it goes back to the while loop.Īnd the process starts over. So after 3, j should be 2 and i should be 4. I am new to python and I am having some problems with this code that should print all the prime numbers that are smaller than 50 using nested loops.
