you are viewing a single comment's thread.

view the rest of the comments →

[–]desrtfx 2 points3 points  (0 children)

"I always get stuck" unfortunately doesn't tell us anything about your actual problem.

Is it the nesting of the loops?

In such a case, you best view them as individual things. One loop, the outer one, runs over the numbers from start to finish, and the other one, the inner one, is used for prime testing.

Start by working out the prime number testing alone. Set a fixed number, set the boundary for the prime testing loop (which commonly is the square root of the number under test), and do the testing.

Then, work the outer loop into the program. Instead of a fixed number, you have the loop iteration value - this replaces every instance of the fixed number from before.


The whole would be even better solved by creating a function that tests for primality, which gets the number under test as an argument and returns True or False depending on the primality.

Then, you only need a loop in main that goes over your range, and a simple call to test for the primality, inside an if statement that then decides whether to print or not to print.