source: python/trunk/Demo/scripts/fact.py

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 1.1 KB
RevLine 
[2]1#! /usr/bin/env python
2
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)...
7
8import sys
9from math import sqrt
10
11def fact(n):
[391]12 if n < 1:
13 raise ValueError('fact() argument should be >= 1')
14 if n == 1:
15 return [] # special case
[2]16 res = []
[391]17 # Treat even factors special, so we can use i += 2 later
18 while n % 2 == 0:
[2]19 res.append(2)
[391]20 n //= 2
[2]21 # Try odd numbers up to sqrt(n)
[391]22 limit = sqrt(n+1)
[2]23 i = 3
24 while i <= limit:
[391]25 if n % i == 0:
[2]26 res.append(i)
[391]27 n //= i
[2]28 limit = sqrt(n+1)
29 else:
[391]30 i += 2
[2]31 if n != 1:
32 res.append(n)
33 return res
34
35def main():
36 if len(sys.argv) > 1:
[391]37 source = sys.argv[1:]
[2]38 else:
[391]39 source = iter(raw_input, '')
40 for arg in source:
[2]41 try:
[391]42 n = int(arg)
43 except ValueError:
44 print arg, 'is not an integer'
45 else:
46 print n, fact(n)
[2]47
48if __name__ == "__main__":
49 main()
Note: See TracBrowser for help on using the repository browser.