File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/sage
2
+ # Factoring integers representing them with polynomials with order=bits
3
+ # Ex: 15 = 2^0 + 2^1 + 2^2 + 2^3 -> (2^0 + 2^1) * (2^0 + 2^2) -> 3*5
4
+ # It works well with mersenne primes but not with other composites.
5
+
6
+ import sys
7
+ sys .setrecursionlimit (100000 )
8
+
9
+ import math
10
+ import gmpy2
11
+ from gmpy2 import mpz
12
+
13
+ def int_to_poly (n ):
14
+ n = mpz (n )
15
+ tmp = ""
16
+ tmp2 = []
17
+ bits = n .bit_length ()
18
+ for j in range (0 ,bits ):
19
+ b = int ((n >> j ) & 1 )
20
+ tmp = str (b ) + tmp
21
+ if b == 1 :
22
+ tmp2 .append ("x^%d " % (j ))
23
+ return "+" .join (tmp2 )
24
+
25
+ def factor_int (n ,verbose = False ):
26
+ if verbose :
27
+ print ("converting to poly:" )
28
+ poly = SR (int_to_poly (n ))
29
+ if verbose :
30
+ print (poly )
31
+ print ("finding factors:" )
32
+ factored = factor (poly )
33
+ if verbose :
34
+ print (factored )
35
+ print ("evaluating terms:" )
36
+ factors = []
37
+ terms = str (factored ).split (")*" )
38
+ ls = len (terms )
39
+ if verbose :
40
+ print (ls )
41
+ if ls > 0 :
42
+ for term in terms :
43
+ term = term .replace ("(" ,"" ).replace (")" ,"" )
44
+ if verbose :
45
+ print (term )
46
+ factors .append (sage_eval (term ,{'x' :2 }))
47
+ return factors
48
+
49
+ if __name__ == "__main__" :
50
+ print (factor_int (Integer (sys .argv [1 ])))
You can’t perform that action at this time.
0 commit comments