-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfac2.sage
116 lines (98 loc) · 2.08 KB
/
fac2.sage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""
How to run:
$sage fac2.sage N n prec trials
:param N: the number to factor
:param n: dimension of lattice
:param prec: precision (integer to correct rounding errors)
:return: prints resulting nearest-to-short vector t, aux vector c
"""
from fpylll import IntegerMatrix, SVP, LLL
import sys
def svp(B):
A = IntegerMatrix.from_matrix(B)
return SVP.shortest_vector(A, pruning=False)
def cvp(B, t):
A = IntegerMatrix.from_matrix(B)
A = LLL.reduction(A, delta=.75) # LLL штатный
# print(A)
#Babai
t = SVP.shortest_vector(A, pruning=False) # 'target'
# print(t)
b = vector(ZZ, t)
A = matrix(ZZ, A)
tt = []
def my_rnd(a):
if a > 0:
return 1
elif a < 0:
return -1
return 0
for j in range((A.nrows()-1), 0, -1):
# c = (1. * b.dot_product(A.row(j)) / A.row(j).dot_product(A.row(j)))
c = my_rnd(1. * b.dot_product(A.row(j)) / A.row(j).dot_product(A.row(j)))
b = b - c * A[j] # check
tt.append(c)
b = vector(ZZ, t) - b
return b, vector(ZZ, tt)
def first_primes(n):
p = 1
P = []
while len(P) < n:
p = next_prime(p)
P += [p]
return P
def is_smooth(x, P):
y = x
for p in P:
while p.divides(y):
y /= p
return abs(y) == 1
# Test if a factoring relation was indeed found.
def test_Schnorr(P, N, n, prec=10):
shuffle(f)
# Scale up and round
def sr(x):
return round(x * 2^prec)
diag = [sr(N*f[i]) for i in range(n)] + [sr(N*ln(N))]
B = diagonal_matrix(diag, sparse=False)
for i in range(n):
B[i, n] = sr(N*ln(P[i]))
print(B)
# Find a "short" vector
b = svp(B)
# Reduce the vector by Babai's algorithm
a = cvp(B, b)
print(a)
"""
e = [b[i] / sr(N*f[i]) for i in range(n)]
u = 1
v = 1
for i in range(n):
assert e[i] in ZZ
if e[i] > 0:
u *= P[i]^e[i]
if e[i] < 0:
v *= P[i]^(-e[i])
return is_smooth(u - v*N, P)
"""
try:
N = int(sys.argv[1])
except:
N = 48567227
try:
n = int(sys.argv[2])
except:
n = 47
try:
pprec = int(sys.argv[3])
except:
pprec = 4
try:
trials = int(sys.argv[4])
except:
trials = 1
N = 48567227
P = first_primes(n)
f = list(range(1, n+1))
for i in range(trials):
test_Schnorr(P, N, n, prec = pprec)