Skip to content

Instantly share code, notes, and snippets.

@GLMeece
Last active June 11, 2020 21:05
Show Gist options
  • Save GLMeece/6414e054a862e5e1be87fd61bf8c6228 to your computer and use it in GitHub Desktop.
Save GLMeece/6414e054a862e5e1be87fd61bf8c6228 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Determine whether integer is a prime or not.
- *Module*: is_prime
- *Platform*: Unix, Windows
- *Author*: [mailto:[email protected]?subject=About is_prime.py|Greg Meece]
"""
# these imports only needed for testing purposes...
import os
import time
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
def is_prime(n):
"""Returns *True* if _n_ is a prime number; otherwise returns *False*."""
import math
if n == 1:
return False
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
max_divisor = math.floor(math.sqrt(n))
for d in range(3, 1 + int(max_divisor), 2):
if n % d == 0:
return False
return True
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
def main():
"""Embedded routines are run as a crude test."""
this_filename = os.path.basename(__file__)
print(f"\nThis module ('{this_filename}') has been called directly.")
print("\n-------------- Exercising is_prime Function ---------------\n")
for n in range(1, 21):
print("Is {:>2} prime? {}!".format(n, is_prime(n)))
print("\n--------------- Timing 'is_prime' Function ----------------\n")
top_int = 100000 # How large a set of integers do you want to time for?
t0 = time.time()
for n in range(1, top_int):
is_prime(n)
t1 = time.time()
print(f"Seconds required to evaluate {top_int:,d} integers: {t1 - t0}\n")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment