Mercurial > cpython-lru_cache-weakref
annotate Demo/scripts/fact.py @ 5817:48b94de85bf3 legacy-trunk
Extensive changes by AMK.
| author | Guido van Rossum <guido@python.org> |
|---|---|
| date | Thu, 17 Jul 1997 16:29:42 +0000 |
| parents | 73758db2f464 |
| children | 2bc66f1df7cc |
| rev | line source |
|---|---|
|
4573
73758db2f464
/usr/local/bin/python -> /usr/bin/env python
Guido van Rossum <guido@python.org>
parents:
1269
diff
changeset
|
1 #! /usr/bin/env python |
| 274 | 2 |
|
504
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
3 # Factorize numbers. |
|
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
4 # The algorithm is not efficient, but easy to understand. |
|
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
5 # If there are large factors, it will take forever to find them, |
|
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
6 # because we try all odd numbers between 3 and sqrt(n)... |
| 274 | 7 |
| 8 import sys | |
| 9 from math import sqrt | |
| 10 | |
| 11 error = 'fact.error' # exception | |
| 12 | |
| 13 def fact(n): | |
| 14 if n < 1: raise error # fact() argument should be >= 1 | |
| 559 | 15 if n == 1: return [] # special case |
| 274 | 16 res = [] |
| 17 # Treat even factors special, so we can use i = i+2 later | |
| 559 | 18 while n%2 == 0: |
| 274 | 19 res.append(2) |
| 20 n = n/2 | |
| 21 # Try odd numbers up to sqrt(n) | |
| 759 | 22 limit = sqrt(float(n+1)) |
| 274 | 23 i = 3 |
| 24 while i <= limit: | |
| 559 | 25 if n%i == 0: |
| 274 | 26 res.append(i) |
| 27 n = n/i | |
|
504
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
28 limit = sqrt(n+1) |
| 274 | 29 else: |
| 30 i = i+2 | |
| 759 | 31 if n != 1: |
| 32 res.append(n) | |
| 274 | 33 return res |
| 34 | |
| 35 def main(): | |
| 36 if len(sys.argv) > 1: | |
| 37 for arg in sys.argv[1:]: | |
|
504
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
38 n = eval(arg) |
| 274 | 39 print n, fact(n) |
| 40 else: | |
| 41 try: | |
| 42 while 1: | |
|
504
eb03977baeeb
Adapt to mixed-mode arithmetic, and added a warning comment.
Guido van Rossum <guido@python.org>
parents:
274
diff
changeset
|
43 n = input() |
| 274 | 44 print n, fact(n) |
| 45 except EOFError: | |
| 46 pass | |
| 47 | |
| 48 main() |
