Saturday, September 14, 2013

A small library of basic prime number algorithms


  • prime(n) tests if a number is prime or not and returns True/False.
  • primeseiveupto(n) returns a list of all prime numbers upto n.
  • numprimelessthan(n) returns the number of primes less than n.
  • primeseiventh(n) returns a list of the first n prime numbers.
  • nthprime(n) returns the nth prime number.
  • primefac(n) lists the prime factors of n in increasing order with repetition, as a list.
  • primefactors(n) return a list of pairs, the first coordinate being the prime factor, and the second coordinate being the corresponding power.
  • numfac(n) returns the number of factors of n, while numpfac(n) returns the number of prime factors of n.
________________________________________________________________________


import math

def prime(n):
 if n==1:
  return False
 else:
  i=2
  k = 1 + math.floor(math.sqrt(n))
  while i<k and n%i != 0:
  i = i+1
  if i == k:
   return True
  else:
   return False

def primeseiveupto(n): 
 seive=[2]
 i=3
 while i<n:
  k=0
  for j in seive:
   if i%j==0:
    k=1
    break
  if k==0:
   seive=seive+[i]
  i=i+1
 return seive

def numprimelessthan(n):
 return len(primeseiveupto(n))

def primeseiventh(n):
 seive=[2]
 i=3
 count=1
 while count<n:
  k=0
  for j in seive:
   if i%j==0:
    k=1
    break
  if k==0:
   seive=seive+[i]
   count=count+1
  i=i+1
 return seive
def nthprime(n):
 seive=[2]
 i=3
 count=1
 while count<n:
  k=0
  for j in seive:
   if i%j==0:
    k=1
    break
  if k==0:
   seive=seive+[i]
   count=count+1
  i=i+1
 return seive[-1]


#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&



def primefaci(n,i):
 k = 1 + math.floor(math.sqrt(n))
 if i>k-1:
  return [n]
 else:
  if n==1:
   return []
  else:
   while i<k and n%i != 0:
    i=i+1
   if i==k and n%k!=0:
    return [n]
   else:
    return [i]+primefaci(n/i,i)

def primefac(n):
 a=primefaci(n,2)
 return a

def listy(l):
 j=l[0]
 a=[]
 counti=0
 for i in l:
  if j==i:
   counti=counti+1
  else:
   a.append((j,counti))
   j=i
   counti=1
 a.append((j,counti))
 return a

def primefactors(n):
 return listy(primefac(n))

#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

def numfac(n):
 j=1
 for i in primefactors(n):
  j=j*(i[1]+1)
 return j

def numpfac(n):
 return len(primefactors(n))



No comments:

Post a Comment