Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. # distutils: language=c++
  2.  
  3. from cython.operator cimport dereference
  4. from libcpp.unordered_map cimport unordered_map
  5.  
  6.  
  7. def primes():
  8. # Yield first two primes
  9. yield 2
  10. yield 3
  11.  
  12. # Initialize composite lookup
  13. cdef unordered_map[int, int] composites
  14.  
  15. # Initialize the inner generator
  16. prime_gen = primes()
  17. next(prime_gen)
  18. next(prime_gen)
  19. cdef int next_prime = 3
  20. cdef int next_square = 9
  21.  
  22. # Loop over candidates
  23. cdef int candidate = 3
  24. cdef int step, next_composite
  25. while True:
  26. candidate += 2
  27.  
  28. # Reached next prime square
  29. if candidate == next_square:
  30. step = 2 * next_prime
  31. composites[candidate + step] = step
  32. next_prime = next(prime_gen)
  33. next_square = next_prime * next_prime
  34. continue
  35.  
  36. # Reached a prime
  37. iterator = composites.find(candidate)
  38. if iterator == composites.end():
  39. yield candidate
  40. continue
  41.  
  42. # Reached a composite
  43. composites.erase(iterator)
  44. step = dereference(iterator).second
  45. next_composite = candidate + step
  46. while composites.count(next_composite):
  47. next_composite += step
  48. composites[next_composite] = step
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement