blob: 03cab8bb85718384725491f8660ec6cf40902b83 [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossumec758ea1991-06-04 20:36:54 +00002
Guido van Rossum1c8230b1991-12-18 13:45:17 +00003# Factorize numbers.
4# The algorithm is not efficient, but easy to understand.
5# If there are large factors, it will take forever to find them,
6# because we try all odd numbers between 3 and sqrt(n)...
Guido van Rossumec758ea1991-06-04 20:36:54 +00007
8import sys
9from math import sqrt
10
Tim Peterse6ddc8b2004-07-18 05:56:09 +000011error = 'fact.error' # exception
Guido van Rossumec758ea1991-06-04 20:36:54 +000012
13def fact(n):
Tim Peterse6ddc8b2004-07-18 05:56:09 +000014 if n < 1: raise error # fact() argument should be >= 1
15 if n == 1: return [] # special case
16 res = []
17 # Treat even factors special, so we can use i = i+2 later
18 while n%2 == 0:
19 res.append(2)
20 n = n/2
21 # Try odd numbers up to sqrt(n)
22 limit = sqrt(float(n+1))
23 i = 3
24 while i <= limit:
25 if n%i == 0:
26 res.append(i)
27 n = n/i
28 limit = sqrt(n+1)
29 else:
30 i = i+2
31 if n != 1:
32 res.append(n)
33 return res
Guido van Rossumec758ea1991-06-04 20:36:54 +000034
35def main():
Tim Peterse6ddc8b2004-07-18 05:56:09 +000036 if len(sys.argv) > 1:
37 for arg in sys.argv[1:]:
38 n = eval(arg)
39 print n, fact(n)
40 else:
41 try:
42 while 1:
43 n = input()
44 print n, fact(n)
45 except EOFError:
46 pass
Guido van Rossumec758ea1991-06-04 20:36:54 +000047
Johannes Gijsbers7a8c43e2004-09-11 16:34:35 +000048if __name__ == "__main__":
49 main()