Ask coding questions

← Back to all posts
Here is my code for prime number generator. When run it prints nothing. Help please.
JacksonVliet

So I coded this prime number generator. When run, it defines 3 variables. The number, what it is being divided by, and if the number was EVER divisible by something. It is intended to print the primes between 2-1000. However, it prints nothing. I think it would work by testing to see if a given number is divisible by anything, and if it isn't then print it. If it is don't. Then increase the number by 1 and repeat until it gets to 1000. However, it does literally nothing when run. Please help

Voters
JacksonVliet
Comments
hotnewtop
Spacecraft

Hi there. I think your problem is on line 10. You put in your IF statement: print == True. I believe what you meant to say is prime == True. If you fix this, it should print out the numbers for you. Here's the whole code:

JacksonVliet

@Spacecraft That is definitely why it was printing nothing, but I changed the code because I also realized that every number is going to be divided by itself, resulting in a remainder of 0 and stopping it from being printed. Now it just prints the powers of two for some reason.

JacksonVliet

@Spacecraft And now I see the problem. When x = number, it sets prime equal to false and won't print it.

JacksonVliet

@Spacecraft I changed the code again, because I realized that it is always going to divide by 1000 at the end, setting prime = true. Which should make it print every number (which it doesn't) so I changed it, and now it prints nothing again. I'm also realizing now that if the last thing the number gets divided by, makes it prime, then it will say the number is prime when it is not. I can't think of a scenario when this will happen in my head, but I'm sure there is a scenario. Is there anyway I could like lock the prime variable once it is set to false?

JacksonVliet

@Spacecraft I have continued to tweak the code a little bit more, and instead of changing the requirements in the IF statement, I changed them in the range. I am dividing by two since any integer won't have a factor larger than itself divided by 2. The break line in the else part of the loop is so that if the number is ever evenly divisible by something, it will break out of the loop and stop the boolean from changing to true and printing the number. Still, any help will be appreciated to help me solve this.

Spacecraft

@JacksonVliet looks like you got it working. Nice job.

Spacecraft

I made a few adjustments to your code so it returns the prime numbers. Give this a try and let me know if you have any questions.

Spacecraft

Updated the code above once more for more simplicity.