Created
August 6, 2016 20:42
-
-
Save mattlewissf/df259a3dfbaeca303c2a4669989fd6fe to your computer and use it in GitHub Desktop.
prime_gaps.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
def gap(g,m,n): | |
primes = [] | |
# finds primes in range | |
for num in xrange(m,n+1,1): # n to be included in range | |
x_half = num / 2 | |
is_prime = all(num % x != 0 for x in xrange(2,x_half+1,1)) | |
if is_prime == True: | |
primes.append(num) | |
for idx, prime in enumerate(primes): | |
try: | |
diff = primes[idx+1] - prime | |
if diff == g: | |
return tuple([prime, primes[idx+1]]) | |
except IndexError: | |
return None | |
# gap(6,100,110) | |
class Test(unittest.TestCase): | |
def test(self): | |
self.assertEqual(gap(2,100,110), (101, 103)) | |
self.assertEqual(gap(4,100,110), (103, 107)) | |
self.assertEqual(gap(6,100,110), None) | |
self.assertEqual(gap(8,300,400), (359, 367)) | |
self.assertEqual(gap(10,300,400), (337, 347)) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment