]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | #! /usr/bin/env python\r |
2 | \r | |
3 | # Factorize numbers.\r | |
4 | # The algorithm is not efficient, but easy to understand.\r | |
5 | # If there are large factors, it will take forever to find them,\r | |
6 | # because we try all odd numbers between 3 and sqrt(n)...\r | |
7 | \r | |
8 | import sys\r | |
9 | from math import sqrt\r | |
10 | \r | |
11 | def fact(n):\r | |
12 | if n < 1:\r | |
13 | raise ValueError('fact() argument should be >= 1')\r | |
14 | if n == 1:\r | |
15 | return [] # special case\r | |
16 | res = []\r | |
17 | # Treat even factors special, so we can use i += 2 later\r | |
18 | while n % 2 == 0:\r | |
19 | res.append(2)\r | |
20 | n //= 2\r | |
21 | # Try odd numbers up to sqrt(n)\r | |
22 | limit = sqrt(n+1)\r | |
23 | i = 3\r | |
24 | while i <= limit:\r | |
25 | if n % i == 0:\r | |
26 | res.append(i)\r | |
27 | n //= i\r | |
28 | limit = sqrt(n+1)\r | |
29 | else:\r | |
30 | i += 2\r | |
31 | if n != 1:\r | |
32 | res.append(n)\r | |
33 | return res\r | |
34 | \r | |
35 | def main():\r | |
36 | if len(sys.argv) > 1:\r | |
37 | source = sys.argv[1:]\r | |
38 | else:\r | |
39 | source = iter(raw_input, '')\r | |
40 | for arg in source:\r | |
41 | try:\r | |
42 | n = int(arg)\r | |
43 | except ValueError:\r | |
44 | print arg, 'is not an integer'\r | |
45 | else:\r | |
46 | print n, fact(n)\r | |
47 | \r | |
48 | if __name__ == "__main__":\r | |
49 | main()\r |