Skip to content

Instantly share code, notes, and snippets.

@macloo
Created December 17, 2013 16:15
Show Gist options
  • Save macloo/8007581 to your computer and use it in GitHub Desktop.
Save macloo/8007581 to your computer and use it in GitHub Desktop.
Simple example of using modulo (modulus) to test for a prime number.
# testing for a prime number - use of modulo (modulus)
# also, good example of a for loop
n = 0
print "\nWe will test a number to find out whether it is prime."
print "Try it with 25. Then try it with 7 or 13."
print "Then try it with any number you like (but not too large a number!)."
n = raw_input("Enter a number: ")
n = int(n)
for counter in range(2, n):
# below, % is the modulus sign
# see http://learnpythonthehardway.org/book/ex3.html
remainder = n % counter
# below, % is used with d to represent a variable
# called formatters, or format strings: %s %d %r
# see http://learnpythonthehardway.org/book/ex5.html
print "%d / %d leaves a remainder of %d" % (n, counter, remainder)
if remainder == 0:
print "Sorry, %d is not a prime number." % n
break
if counter == n - 1:
print "\nHooray! %d is a prime number.\n" % n
@macloo
Copy link
Author

macloo commented Dec 17, 2013

Questions for students:

  1. Why do we need line 10?
  2. In line 12, why do we start with 2? Why not 0? Why not 1?
  3. In line 12, we end with n. In line 26, we have n - 1. Why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment