Download code
From LiteratePrograms
Back to Factorials_with_prime_factorization_(Python)
Download for Windows: single file, zip
Download for UNIX: single file, zip, tar.gz, tar.bz2
prime_factorial.py
1 # Copyright (c) 2010 the authors listed at the following URL, and/or 2 # the authors of referenced articles or incorporated external code: 3 # http://en.literateprograms.org/Factorials_with_prime_factorization_(Python)?action=history&offset=20060517215138 4 # 5 # Permission is hereby granted, free of charge, to any person obtaining 6 # a copy of this software and associated documentation files (the 7 # "Software"), to deal in the Software without restriction, including 8 # without limitation the rights to use, copy, modify, merge, publish, 9 # distribute, sublicense, and/or sell copies of the Software, and to 10 # permit persons to whom the Software is furnished to do so, subject to 11 # the following conditions: 12 # 13 # The above copyright notice and this permission notice shall be 14 # included in all copies or substantial portions of the Software. 15 # 16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 # 24 # Retrieved from: http://en.literateprograms.org/Factorials_with_prime_factorization_(Python)?oldid=4814 25 26 def multiplicity(n, p): 27 """Return the power of the prime number p in the 28 factorization of n!""" 29 if p > n: return 0 30 if p > n//2: return 1 31 q, m = n, 0 32 while q >= p: 33 q //= p 34 m += q 35 return m 36 37 def primes(n): 38 """Generate a list of the prime numbers [2, 3, ... m] where 39 m is the largest prime <= n.""" 40 n = n + 1 41 sieve = range(n) 42 sieve[:2] = [0, 0] 43 for i in xrange(2, int(n**0.5)+1): 44 if sieve[i]: 45 for j in xrange(i**2, n, i): 46 sieve[j] = 0 47 # Filter out the composites, which have been replaced by 0's 48 return [p for p in sieve if p] 49 50 def powproduct(ns): 51 """Compute the explicit value of a factored integer 52 given as a list of (base, exponent) pairs.""" 53 if not ns: 54 return 1 55 units = 1 56 multi = [] 57 for base, exp in ns: 58 if exp == 0: 59 continue 60 elif exp == 1: 61 units *= base 62 else: 63 if exp % 2: 64 units *= base 65 multi.append((base, exp//2)) 66 return units * powproduct(multi)**2 67 68 def factorial(n): 69 return powproduct((p, multiplicity(n, p)) for p in primes(n)) 70
