Moved 6 to 11 from ipython to python.

This commit is contained in:
2019-07-14 16:51:31 -04:00
parent b246d56acd
commit 86e68eeee2
8 changed files with 289 additions and 3 deletions

View File

@@ -5,6 +5,9 @@ except ModuleNotFoundError:
def prime_factors(n):
"""
:param n: number for which prime factors should be returned
"""
# TODO: Look into using a prime wheel instead.
factors = []
rest = n
@@ -24,4 +27,83 @@ def prime_factors(n):
def prime_factors_count(n):
"""
:param n: numober for which prime factor counts are returned
:returns: a dict where they key is a prime vactor and the value
the count of how of that value occurs
"""
return get_item_counts(prime_factors(n))
def is_prime(n):
"""Returns True if n is prime and False otherwise.
:param n: number to be checked
"""
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
def prime_nth(n):
"""Returns the nth prime number. The first number
is 1 indexed, i.e. n = 1 -> 2, n = 2 -> 3, etc.
:param n:
"""
if n == 1:
return 2
if n == 2:
return 3
p = 5
i = 3
while i < n:
p = p + 2
if is_prime(p):
i += 1
return p
def primes(n_max):
"""
Returns a list of all primes smaller n based
on sieve of erasthones algorithm.
If bitarray module is installed it will be used
for the array, otherwise a regular Python list is
used. The function should work for much larger
numbers with bitarray.
:param n_max:
"""
try:
import bitarray
b = bitarray.bitarray(n_max)
b.setall(True)
except ModuleNotFoundError:
b = [True for _ in range(n_max)]
n = 1
b[n - 1] = False
while n * n <= n_max:
if b[n - 1] is True:
for i in range(n + n, n_max + 1, n):
b[i - 1] = False
n += 1
ps = []
for i in range(1, n_max + 1):
if b[i - 1]:
ps.append(i)
return ps