A simple prime-number bot, in python. WIP
mastodon
python
fediverse
bot
mathematics
prime-numbers

sieve.py 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Sieve of Eratosthenes, in python
  2. from numpy import array, zeros, int8
  3. from time import process_time
  4. def sieve(to):
  5. """Construct a sieve of Eratosthenes up to the value of 'to'; return all
  6. primes below this number.
  7. """
  8. zarr = zeros(to, int8)
  9. zarr[0:2] = 1
  10. for i in range(2, to):
  11. if zarr[i] == 1:
  12. continue
  13. for x in range(i, ((to - 1) // i) + 1):
  14. zarr[i * x] = 1
  15. avals = array(range(to))
  16. return avals[zarr[range(to)] == 0]
  17. def sieval(to):
  18. """Run sieve algorithm up to 'to'; return process time, number of primes,
  19. and last prime calculated (in that order).
  20. 'to' must be greater than 2.
  21. """
  22. t1 = process_time()
  23. sh = sieve(to)
  24. te = process_time() - t1
  25. ls = len(sh)
  26. return te, ls, sh[ls - 1]
  27. def sievemsg(to):
  28. """Format sieval output for sieve up to 'to'
  29. 'to' must be greater than 2.
  30. """
  31. t, n, l = sieval(to)
  32. rs = ("There are {1} prime numbers smaller than {3}; the largest is {2}. This "
  33. "calculation took {0:.2f} seconds via the sieve of "
  34. "Eratosthenes.".format(t, n, l, to))
  35. return rs