Advertisement
triclops200

Decently Efficient sieve

Jul 9th, 2013
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. from __future__ import print_function
  2. import time
  3. import sys
  4. import math
  5. try:
  6.     import numpypy
  7. except:
  8.     pass
  9. import numpy
  10. def gcd(x,y):
  11.     if x%y == 0:
  12.         return y
  13.     return gcd(y,x%y)
  14. def build_sieve(n):
  15.     nums = numpy.arange(2,n+1,dtype=numpy.int32)
  16.     primes = []
  17.     ct = int(math.sqrt(n))
  18.     sp = int(ct/50)
  19.     x = 2
  20.     count = 0
  21.     tick = 0
  22.     print("\r[%50s]"%("="*tick),end="")
  23.     while x <= ct:
  24.         if x >= tick*sp+sp:
  25.             print("\r[%50s]"%("="*tick),end="")
  26.             tick += 1
  27.             sys.stdout.flush()
  28.         nums = nums[nums%x != 0]
  29.         primes.append(x)
  30.         x = nums[0]
  31.     print("\r"+" "*53,end="\r")
  32.     for x in nums:
  33.         primes.append(x)
  34.     return primes
  35. start = time.time()
  36. primes = build_sieve(int(raw_input("> ")))
  37. elapsed = time.time() - start
  38. print("You took %f seconds to calculate %d primes"%(elapsed,len(primes)))
  39. yeses = set(["yes","y","yeah","yep"])
  40. noes = set(["no","n","nope"])
  41. res = "huh"
  42. while res not in noes and res not in yeses:
  43.     res = raw_input("Would you like to save to a file [y/n]? ").lower()
  44.     if res not in noes and res not in yeses:
  45.         print("Please type y or n")
  46. if res in yeses:
  47.     fname = raw_input("File Name: ")
  48.     f = open(fname,"w")
  49.     count = 0
  50.     l = len(primes)
  51.     sp = int(l/3000)
  52.     for x in primes:
  53.         f.write(str(x))
  54.         f.write("\n")
  55.         if int(count)%sp == 0:
  56.             print("\r%5.1f%%"%(100.0*count/l),end="")
  57.             sys.stdout.flush()
  58.         count += 1
  59.     print("\r"+" "*50,end="\r")
  60.     f.close()
  61. else:
  62.     print("Okay then, goodbye!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement