nextprime.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env pypy3
  2. #
  3. # Permission to use, copy, modify, and/or distribute this software for
  4. # any purpose with or without fee is hereby granted.
  5. #
  6. # THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
  7. # WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
  8. # OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
  9. # FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
  10. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
  11. # AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  12. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  13. #
  14. import argparse
  15. from math import ceil, sqrt
  16. def isprime(n):
  17. if (not n % 2 and n != 2) or (not n % 3 and n != 3):
  18. return False
  19. for i in range(5, int(ceil(sqrt(n)) + 0.5) + 1, 6):
  20. if not n % i or not n % (i + 2):
  21. return False
  22. return True if n >= 2 else False
  23. def nextprime(n, prev):
  24. if prev and n < 2:
  25. raise Exception("Error: Number is less than 2.")
  26. n = max(n, 2)
  27. if n == 2:
  28. return n
  29. if isprime(n):
  30. return n
  31. if n % 2 == 0:
  32. n += -1 if prev else 1
  33. while True:
  34. if isprime(n):
  35. return n
  36. n += -2 if prev else 2
  37. if __name__ == "__main__":
  38. p = argparse.ArgumentParser(
  39. description="Find the next (or previous) prime number, given a start number.")
  40. p.add_argument("-p", "--prev", action="store_true",
  41. help="Find the previous prime instead of the next prime.")
  42. p.add_argument("number", type=int)
  43. args = p.parse_args()
  44. print(nextprime(args.number, args.prev))
  45. # vim: ts=4 sw=4 expandtab