Last active
August 29, 2015 14:04
-
-
Save 0xquad/4269776fa7bb611e93ab to your computer and use it in GitHub Desktop.
Simple way to calculate prime factors
This file contains hidden or 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
#!/usr/bin/python3 | |
# | |
# Copyright (c) 2014, Alexandre Hamelin <alexandre.hamelin gmail.com> | |
# | |
# Small program that calculates primes and print them on screen. | |
import sys | |
def primes(): | |
import itertools | |
primes_list = [2, 3, 5] | |
deltas = itertools.cycle([2, 2, 4, 2]) | |
diffs = [0, 1, 2] | |
maxdiff = 0 | |
for i, p in enumerate(primes_list): | |
yield p, diffs[i] | |
n = p | |
while True: | |
try: | |
n += deltas.__next__() | |
N = n ** .5 # sqrt() | |
is_prime = all([n % p != 0 for p in primes_list if p < N]) | |
if is_prime: | |
primes_list.append(n) | |
diffs.append(n - primes_list[-2]) | |
if diffs[-1] > maxdiff: | |
maxdiff = diffs[-1] | |
print('found new maxdiff {0} at {1}'.format(str(maxdiff), n)) | |
#yield n, diffs[-1] | |
except KeyboardInterrupt: | |
import time | |
try: | |
print('\nat prime {0}'.format(n)) | |
time.sleep(1) | |
except KeyboardInterrupt: | |
break | |
for p, diff in primes(): | |
#print(str(p) + ' ', end='') | |
print(str(diff) + ' ', end='') # show differences instead | |
sys.stdout.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment