blob: 71fcda2ed0d3077ec2e56f36e9fa6f71a5079e42 [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
Guido van Rossumec758ea1991-06-04 20:36:54 +000011def fact(n):
Georg Brandl22fff432009-10-27 20:19:02 +000012 if n < 1:
13 raise ValueError('fact() argument should be >= 1')
14 if n == 1:
15 return [] # special case
Tim Peterse6ddc8b2004-07-18 05:56:09 +000016 res = []
Georg Brandl22fff432009-10-27 20:19:02 +000017 # Treat even factors special, so we can use i += 2 later
18 while n % 2 == 0:
Tim Peterse6ddc8b2004-07-18 05:56:09 +000019 res.append(2)
Georg Brandl22fff432009-10-27 20:19:02 +000020 n //= 2
Tim Peterse6ddc8b2004-07-18 05:56:09 +000021 # Try odd numbers up to sqrt(n)
Georg Brandl22fff432009-10-27 20:19:02 +000022 limit = sqrt(n+1)
Tim Peterse6ddc8b2004-07-18 05:56:09 +000023 i = 3
24 while i <= limit:
Georg Brandl22fff432009-10-27 20:19:02 +000025 if n % i == 0:
Tim Peterse6ddc8b2004-07-18 05:56:09 +000026 res.append(i)
Georg Brandl22fff432009-10-27 20:19:02 +000027 n //= i
Tim Peterse6ddc8b2004-07-18 05:56:09 +000028 limit = sqrt(n+1)
29 else:
Georg Brandl22fff432009-10-27 20:19:02 +000030 i += 2
Tim Peterse6ddc8b2004-07-18 05:56:09 +000031 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:
Georg Brandl22fff432009-10-27 20:19:02 +000037 source = sys.argv[1:]
Tim Peterse6ddc8b2004-07-18 05:56:09 +000038 else:
Georg Brandl22fff432009-10-27 20:19:02 +000039 source = iter(input, '')
40 for arg in source:
Tim Peterse6ddc8b2004-07-18 05:56:09 +000041 try:
Georg Brandl22fff432009-10-27 20:19:02 +000042 n = int(arg)
43 except ValueError:
44 print(arg, 'is not an integer')
45 else:
46 print(n, fact(n))
Guido van Rossumec758ea1991-06-04 20:36:54 +000047
Johannes Gijsbers7a8c43e2004-09-11 16:34:35 +000048if __name__ == "__main__":
49 main()