#!/usr/bin/python ''' primechecker.py Jeff Ondich, 9 May 2012 A small sample class to be tested by unittest-based test cases. See primetests.py for the rest of this sample. ''' class PrimeChecker: def __init__(self, maxInteger): self.maxInteger = 0 self.initializeSieve(maxInteger) def initializeSieve(self, maxInteger): ''' Initializes a Sieve of Eratothsenes up to but not including maxInteger. Precondition: maxInteger is an integer greater than 1. ''' assert type(maxInteger) == type(0) assert maxInteger > 1 if maxInteger > self.maxInteger: self.maxInteger = maxInteger self.sieve = [0] * self.maxInteger self.sieve[0] = 1 self.sieve[1] = 1 currentPrime = 2 while currentPrime < self.maxInteger: k = currentPrime * 2 while k < self.maxInteger: self.sieve[k] = 1 k += currentPrime currentPrime += 1 while currentPrime < self.maxInteger and self.sieve[currentPrime] == 1: currentPrime += 1 def getMaxInteger(self): return self.maxInteger def getPrimesBelow(self, n): ''' Returns the list of primes strictly less than n, sorted in increasing order. ''' self.initializeSieve(n) primes = [k for k in range(n) if self.sieve[k] == 0] return primes def isPrime(self, n): ''' Returns True if the specified integer is prime, and False otherwise. Preconditions: n is an integer between 1 and getMaxInteger(), inclusive. Raises TypeError if n is not an integer, or ValueError if n is not in the proper range. ''' if type(n) != type(0): raise TypeError('Parameter (type %s) must have type %s' % (str(type(n)), str(type(0)))) if n < 1 or n > self.maxInteger: raise ValueError('Integer parameter (%d) is out of range (1 to %d)' % (n, self.maxInteger)) assert self.maxInteger == len(self.sieve) if n < 2: return False return self.sieve[n] == 0