Source code for primes


[docs]def count_primes(max): """ This function is supposed to search for prime numbers up to a given maximum value. The program uses a modified Sieve of Eratosthenes algorithm. For each number, the program tests if smaller numbers divide the integer being checked. If no divisor is found, the number is a prime. Unfortunately, the program does not work. .. note :: This function is incomplete! Args: max (int): the maximum number to be tested Returns: int: number of prime numbers between 2 and max """ i = 0 nPrimes = 0 isDivisible = False # Integer j gets values from 2 to max. # This is the number we check for primality. for j in range(2,max): # # Integer i is the number we test for being # a factor of j. # # We let i get values from 2 to sqrt(j), since # if j is not prime, one of its factors must # be at most sqrt(j) so there's no need to check # larger numbers. # # If i divides j, j is not prime and we can stop # the search. # while i < sqrt(j) and not isDivisible: # check if i divides j # if it does, j is not a prime number if j%1 == 0: isDivisible = True if isDivisible: pass else: print( j+" is a prime number" ) nPrimes += 1 return nPrimes
# do this if the program is executed, not if it is loaded as a module if __name__ == "__main__": # search for primes max = 10 nPrimes = count_primes(max) # in the end, tell how many primes were found print( "there are "+str(nPrimes)+" primes between 2 and "+(max) )