Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # function: factor_integer()
- def factor_integer(n):
- """
- prints the integer and the list of its factors
- E.g.
- >>> factor_integer(198273646782734)
- 198,273,646,782,734 [2, 17, 2243, 2599900957]
- Employs a data file of primes to 100 million (5,761,459 primes),
- thereby ensuring quick factorization of any integer up to
- 10 quadrillion (1e17).
- This data file may be downloaded from
- http://www.rcblue.com/Misc2/primes_to_100_million.dat
- gmpy2 is available at http://code.google.com/p/gmpy/
- """
- import pickle
- import os.path
- import gmpy2
- from gmpy2 import is_prime
- def int_commas(n):
- """
- inserts commas into integers and returns the string
- E.g. -12345678 -> -12,345,789
- """
- return format(n, ',d')
- def test_of_list_of_prime_factors_of_int(n, list_):
- """
- Remains silent unless error detected.
- """
- error_flag = 0
- for e in list_:
- if not is_prime(e):
- error_flag = 1
- print(e, "is not prime!")
- if error_flag == 1:
- print("Not all elements of list of factors are prime! (n = ", n,")", sep='')
- product = 1
- for e in list_:
- product *= e
- if n != product:
- print("Product of factors doesn't equal n! (n = ", n,")", sep='')
- def load_pickled_data(path):
- if os.path.getsize(path) == 0:
- #The file exists, but is empty: leave it alone
- pass
- elif os.path.exists(path):
- #The file exists and is not empty: use it
- with open(path, "rb") as f:
- data = pickle.load(f)
- D = data
- primes = D
- return primes
- def int_factors(n, primes):
- factors = []
- #limit = int(n**.5) + 1
- if is_prime(n):
- return [int(n)]
- if n == 1:
- return []
- for x in primes:
- while n % x == 0:
- factors.append(int(x))
- n = n // x
- if is_prime(n):
- factors.append(int(n))
- return factors
- while True:
- x += 2
- while n % x == 0:
- factors.append(int(x))
- n = n // x
- if is_prime(n):
- factors.append(n)
- return factors
- path = 'C:\P32Working\Data\primes_to_100_million.dat'
- primes = load_pickled_data(path)
- factors = int_factors(n, primes)
- test_of_list_of_prime_factors_of_int(n, factors)
- print(int_commas(n), factors)
- print(factor_integer(94583726378))
- """
- OUTPUT:
- 94,583,726,378 [2, 19, 2489045431]
- """
Advertisement
Add Comment
Please, Sign In to add comment