Show use of range() step argument nicely.
[python.git] / Demo / scripts / fact.py
blobc030187e7b0ce90e6dbff4ad21ec40b6ea396bc8
1 #! /usr/bin/env python
3 # 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)...
8 import sys
9 from math import sqrt
11 def fact(n):
12 if n < 1: raise ValueError # fact() argument should be >= 1
13 if n == 1: return [] # special case
14 res = []
15 # Treat even factors special, so we can use i = i+2 later
16 while n%2 == 0:
17 res.append(2)
18 n = n//2
19 # Try odd numbers up to sqrt(n)
20 limit = sqrt(float(n+1))
21 i = 3
22 while i <= limit:
23 if n%i == 0:
24 res.append(i)
25 n = n//i
26 limit = sqrt(n+1)
27 else:
28 i = i+2
29 if n != 1:
30 res.append(n)
31 return res
33 def main():
34 if len(sys.argv) > 1:
35 for arg in sys.argv[1:]:
36 n = eval(arg)
37 print n, fact(n)
38 else:
39 try:
40 while 1:
41 n = input()
42 print n, fact(n)
43 except EOFError:
44 pass
46 if __name__ == "__main__":
47 main()