Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've added comments on the sides to explain what each line does:</p> <pre><code>from math import * # imports everything from the math module def main(): n = abs(input("Enter a number: ")) # gets input from the user i = 2 # starts off at 2 because all input is divisble by 1 msg = 'is a prime number.' # the message is initially set while i &lt;= sqrt(n): if n % i == 0: # if 'i' divides evenly into n msg = 'is not a prime number.' # only set if it isn't a prime i = i + 1 # increases 'i' by 1 so it can check every value up to the square-root of 'n' (to see if it divides evenly) print n, msg main() </code></pre> <p>The program has to go through every value of <code>i</code> (up to the square-root of <code>n</code>) so that every possible factor is checked.</p> <p>This is sort of a rough-prime checker, and inefficient for large numbers that aren't prime: If the input was a number like <code>1234567890</code>, it will iterate through every number up to the square root of that number, which is <code>35147</code> (rounded up). Using <code>return</code> statements break the loop, so the first number you check, <code>2</code>, it is declared not prime since it is evenly divisible by <code>2</code>. By using <code>return</code>, it will stop the function, and save you 35,146 calculations. That isn't a massive number (for computers, at least) but it's still more memory-efficient and takes less time.</p> <pre><code>def isPrime(n): '''Checks if 'n' is prime.''' from math import sqrt if n == 0 or n == 1: return False else: for check in range(2, int(sqrt(n))+1): if n % check == 0: return False return True </code></pre>
    singulars
    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. This table or related slice is empty.
    1. 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