| Index: > A B C D E F G H I J K L M N O P Q R S T U V W X Y Z |
|
|||||
We can describe a recursive algorithm to perform such factorizations: given a number n
Note that we need to test only primes pi such that pi ≤ √n.
Suppose we wish to factorize 9438. 9438/2 = 4719, with no remainder so 2 is a factor. We repeat the algorithm with 4719. 4719/2 = 2359.5, so 2 is not a factor. 4719/3 = 1573, so 3 is a factor. The first prime number which 1573 is divisible by is 11. 1573/11 = 143. Similarly the first prime number which 143 is divisible by is 11. 143/11 = 13. 13 is itself a prime.
Thus working back, we have 9438 = 2*3*11*11*13
Here is the example in Python:
import sys,math def factorize(n): def isPrime(n): return not [x for x in xrange(2,int(math.sqrt(n))) if n%x == 0] primes = [] candidates = xrange(2,n+1) candidate = 2 while not primes and candidate in candidates: if n%candidate == 0 and isPrime(candidate): primes = primes + [candidate] + factorize(n/candidate) candidate += 1 return primes print factorize(int(sys.argv[1]))output:
python factorize.py 9438 [2, 3, 11, 11, 13]The algorithm described above works fine for small n, but becomes impractical as n gets larger. For example, for an 18- digit (or 60 bit) number, all primes below about 1,000,000,000 may need to be tested, which is taxing even for a computer. Adding two decimal digits to the original number will multiply the computation time by 10.
The difficulty (large time complexity) of factorization makes it a suitable basis for modern cryptography.
See also: Euler's Theorem, Integer factorization, Trial division