Example #1
0
def prime_n(n):
  '''Return the n'th prime.'''
  if n == 0:
    return 1
  j = 0
  count = 1
  while count != n:
    primes = sieve_erato(int(2**j * log(n) * n))
    count = 1
    for i, elem in enumerate(primes):
      if elem:
        count += 1
        if count == n:
          break
    j += 1
  return 2*i + 3
Example #2
0
def segmented_sieve(L, R, B):
  '''Perform a segmented Sieve of Eratosthenes.'''

  # Typechecking
  if (R - L) % B != 0:
    raise ValueError('segmented_sieve(): B must divide R - L')

  # First compute the primes less than sqrt(R).
  divisors = sieve_erato(int(sqrt(R)))

  Q = [-(L + 1 + (2*i + 3)) / 2 % (2*i + 3) if n != 0 else 0 for i, n in
    enumerate(divisors)]
  for block in xrange((R - L) / (2 * B)):
    lst = bt.bitarray(B)
    lst.setall(True)
    for i, p in enumerate(divisors):
      if p:
        lst[Q[i]::2*i+3] = False
    Q = [(Q[i] - B) % (2*i + 3) if n != 0 else 0 for i, n in
      enumerate(divisors)]
    yield lst