Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your script, regardless of if the number is divisble by 2 or not, it breaks the loop immediately. I've reindented the code and this is probably closer to what you were trying to do.</p> <p>In your original code, if the number <em>is divisible by 2</em> (first number in the <code>range(2,number)</code>, then you break the loop and if it <em>is not divisible</em> you also break the loop. So all odd numbers, like 9, looked like primes.</p> <p>The <code>else</code> keyword after a <code>for</code> loop is run <em>iff</em> the loop exits normally. So the "is prime" part will only be printed if no divisor is found.</p> <pre><code>for number in range(0,1000): for x in range(2,number): if(number % x == 0): print number,"divisible by",x break else: print number, "is prime" </code></pre> <p>You can see this is anction here: <a href="http://codepad.org/XdS413LR" rel="nofollow">http://codepad.org/XdS413LR</a></p> <p>Also, this is a naive algorithm (not a critique of the code, exploring simple algorithms is a useful study), but you can make a little more efficient. Technically you only need to check as far as the sqare root of <code>number</code>, as any number larger than the square root must have a complement that is less than the square root, which should have already been encountered. So the logic in the code can be changed to:</p> <pre><code>from math import sqrt for number in range(0,1000): for x in range(2,int(sqrt(number/2))): # Rest of code as above. </code></pre> <p>That said there are many ways that you can optimise the checking or discovery of prime numbers that are worth investigating if you get the chance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload