Skip to content

Instantly share code, notes, and snippets.

@FrankHassanabad
Created June 20, 2018 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrankHassanabad/b31a961f5907ee2ebe5b6af07e9bbfa0 to your computer and use it in GitHub Desktop.
Save FrankHassanabad/b31a961f5907ee2ebe5b6af07e9bbfa0 to your computer and use it in GitHub Desktop.
Correction fo prime numbers
import math
# This as written will fail saying 1 and 4 are prime.
# Those two numbers are not prime.
# Also, checking up to square root is more efficient.
def IsPrime(n):
if (n == 1 or n == 4):
return False
for divisor in range(2, int(math.ceil(math.sqrt(n)))):
if n % divisor == 0:
return False
return True
# See table testing from earlier bathroom conversations
# where you would compare this to a table of known prime numbers
# This is ad-hoc for testing purposes only
for i in range(1, 100):
isPrime = IsPrime(i)
if isPrime:
print(i, IsPrime(i))
@FrankHassanabad
Copy link
Author

FrankHassanabad commented Jun 20, 2018

As written this will falsely display 1 and 4 as prime numbers. See ad-hoc unit test below which when run displays these two as True

(1, True)
(4, True)
import math

# This as written will fail saying 1 and 4 are prime.
# Those two numbers are not prime.
# Also, checking up to square root is more efficient.
# I don't know why during the refactor the dev changed the range suddenly. They introduced a bug by doing that.
def IsPrime(n):
        if (n == 1 or n == 4):
                return False
        for divisor in range(2, int(math.ceil(math.sqrt(n)))):
                if n % divisor == 0:
                        return False
        return True


# See table testing from earlier bathroom conversations
# where you would compare this to a table of known prime numbers
# This is ad-hoc for testing purposes only below but shows the dangers
# of not having unit tests. Again, see earlier bathroom conversations.
for i in range(1, 100):
        isPrime = IsPrime(i)
        if isPrime:
                print(i, IsPrime(i))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment