Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Primality quiz
#!/usr/bin/env python3
# Primality quiz
# Use the commandline argument "p" to show the list
#
# http://sekika.github.io/2016/12/13/Primality/
### Parameters
rep=10 # Numbers of questions
# Control the numbers for questions
# The numbers from first to last, excluding obvious numbers will be shown.
# Obvious numbers include
# (1) Multiple of 2 and 5
# (2) Multiple of 3 (when three=True)
# or Numbers where all digits are multiple of 3 (when three=False)
# (3) Numbers in the obvious list
first=29 # Smallest number
last=400 # Largest number
three=False # Make multiple of 3 as obvious
obvious=[7,11,13,21,27,49,77,81,777] # Obvious numbers
########################
import math, random, sys
# Sieve of Eratosthenes; divisor[n] is the minimum divisor
divisor = [i for i in range(0,last+1)]
lastprime=1
for prime in divisor:
if prime > math.sqrt(last): break
if prime <= lastprime: continue
lastprime=prime
for non_prime in range(2 * prime, last+1, prime):
divisor[non_prime] = min(prime, divisor[non_prime])
# factorize(n) shows factorization
def factorize(n):
n = int(n)
if n == divisor[n]:
return str(n)
else:
return str(divisor[n])+' * '+factorize(n/divisor[n])
# Prepare primes and nonprimes for questions
prime=[]
nonprime=[]
for n in range(first, last+1):
if three:
modthree=n % 3
else:
modthree=sum([int(c)%3 for c in str(n)]) # All the digits are multiple of 3?
if (n % 2)*(n % 5)*modthree != 0 and not n in obvious:
if n==divisor[n]:
prime.append(n)
else:
nonprime.append(n)
# Read command line argument
if len(sys.argv) > 1:
arg = sys.argv[1]
else:
arg = ""
##### Print mode (command line argument = "p")
if arg == "p":
print ('List of primes')
print (prime)
print ('List of composite numbers')
for n in nonprime:
print (n, '=', factorize(n))
sys.exit()
##### Primality quiz
# Prepare the questions
while len(prime)<rep:
prime.extend(prime)
random.shuffle(prime)
while len(nonprime)<rep:
nonprime.extend(nonprime)
random.shuffle(nonprime)
question=prime[:rep]
question.extend(nonprime[:rep])
random.shuffle(question)
question=question[:rep]
# Main loop
print (rep, 'questions for primality.')
print (question)
for n in question:
key=input(str(n)+' is prime? Type return to show the answer. ')
if n==divisor[n]:
print ('Prime!')
else:
print ('Composite.',n, '=', factorize(n))
@sekika

This comment has been minimized.

Show comment
Hide comment
Owner

sekika commented Dec 13, 2016

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