forked from williamstein/ent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ent.py
1444 lines (1329 loc) · 40.7 KB
/
ent.py
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################################################
# ent.py -- Element Number Theory
# (c) William Stein, 2004
##################################################
from random import randrange
from math import log, sqrt
##################################################
## Greatest Common Divisors
##################################################
def gcd(a, b): # (1)
"""
Returns the greatest commond divisor of a and b.
Input:
a -- an integer
b -- an integer
Output:
an integer, the gcd of a and b
Examples:
>>> gcd(97,100)
1
>>> gcd(97 * 10**15, 19**20 * 97**2) # (2)
97L
"""
if a < 0: a = -a
if b < 0: b = -b
if a == 0: return b
if b == 0: return a
while b != 0:
(a, b) = (b, a%b)
return a
##################################################
## Enumerating Primes
##################################################
def primes(n):
"""
Returns a list of the primes up to n, computed
using the Sieve of Eratosthenes.
Input:
n -- a positive integer
Output:
list -- a list of the primes up to n
Examples:
>>> primes(10)
[2, 3, 5, 7]
>>> primes(45)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
"""
if n <= 1: return []
X = [i for i in range(3,n+1) if i%2 != 0] # (1)
P = [2] # (2)
sqrt_n = sqrt(n) # (3)
while len(X) > 0 and X[0] <= sqrt_n: # (4)
p = X[0] # (5)
P.append(p) # (6)
X = [a for a in X if a%p != 0] # (7)
return P + X # (8)
##################################################
## Integer Factorization
##################################################
def trial_division(n, bound=None):
"""
Return the smallest prime divisor <= bound of the
positive integer n, or n if there is no such prime.
If the optional argument bound is omitted, then bound=n.
Input:
n -- a positive integer
bound - (optional) a positive integer
Output:
int -- a prime p<=bound that divides n, or n if
there is no such prime.
Examples:
>>> trial_division(15)
3
>>> trial_division(91)
7
>>> trial_division(11)
11
>>> trial_division(387833, 300)
387833
>>> # 300 is not big enough to split off a
>>> # factor, but 400 is.
>>> trial_division(387833, 400)
389
"""
if n == 1: return 1
for p in [2, 3, 5]:
if n%p == 0: return p
if bound == None: bound = n
dif = [6, 4, 2, 4, 2, 4, 6, 2]
m = 7; i = 1
while m <= bound and m*m <= n:
if n%m == 0:
return m
m += dif[i%8]
i += 1
return n
def factor(n):
"""
Returns the factorization of the integer n as
a sorted list of tuples (p,e), where the integers p
are output by the split algorithm.
Input:
n -- an integer
Output:
list -- factorization of n
Examples:
>>> factor(500)
[(2, 2), (5, 3)]
>>> factor(-20)
[(2, 2), (5, 1)]
>>> factor(1)
[]
>>> factor(2004)
[(2, 2), (3, 1), (167, 1)]
"""
if n in [-1, 0, 1]: return []
if n < 0: n = -n
F = []
while n != 1:
p = trial_division(n)
e = 1
n /= p
while n%p == 0:
e += 1; n /= p
F.append((p,e))
F.sort()
return F
def is_squarefree(n):
"""
Returns True if and only if n is not divisible by the square of an integer > 1.
"""
if n==0:
return False
for p, r in factor(n):
if r>1:
return False
return True
##################################################
## Linear Equations Modulo $n$
##################################################
def xgcd(a, b):
"""
Returns g, x, y such that g = x*a + y*b = gcd(a,b).
Input:
a -- an integer
b -- an integer
Output:
g -- an integer, the gcd of a and b
x -- an integer
y -- an integer
Examples:
>>> xgcd(2,3)
(1, -1, 1)
>>> xgcd(10, 12)
(2, -1, 1)
>>> g, x, y = xgcd(100, 2004)
>>> print g, x, y
4 -20 1
>>> print x*100 + y*2004
4
"""
if a == 0 and b == 0: return (0, 0, 1)
if a == 0: return (abs(b), 0, b/abs(b))
if b == 0: return (abs(a), a/abs(a), 0)
x_sign = 1; y_sign = 1
if a < 0: a = -a; x_sign = -1
if b < 0: b = -b; y_sign = -1
x = 1; y = 0; r = 0; s = 1
while b != 0:
(c, q) = (a%b, a/b)
(a, b, r, s, x, y) = (b, c, x-q*r, y-q*s, r, s)
return (a, x*x_sign, y*y_sign)
def inversemod(a, n):
"""
Returns the inverse of a modulo n, normalized to
lie between 0 and n-1. If a is not coprime to n,
raise an exception (this will be useful later for
the elliptic curve factorization method).
Input:
a -- an integer coprime to n
n -- a positive integer
Output:
an integer between 0 and n-1.
Examples:
>>> inversemod(1,1)
0
>>> inversemod(2,5)
3
>>> inversemod(5,8)
5
>>> inversemod(37,100)
73
"""
g, x, y = xgcd(a, n)
if g != 1:
raise ZeroDivisionError, (a,n)
assert g == 1, "a must be coprime to n."
return x%n
def solve_linear(a,b,n):
"""
If the equation ax = b (mod n) has a solution, return a
solution normalized to lie between 0 and n-1, otherwise
returns None.
Input:
a -- an integer
b -- an integer
n -- an integer
Output:
an integer or None
Examples:
>>> solve_linear(4, 2, 10)
8
>>> solve_linear(2, 1, 4) == None
True
"""
g, c, _ = xgcd(a,n) # (1)
if b%g != 0: return None
return ((b/g)*c) % n
def crt(a, b, m, n):
"""
Return the unique integer between 0 and m*n - 1
that reduces to a modulo n and b modulo m, where
the integers m and n are coprime.
Input:
a, b, m, n -- integers, with m and n coprime
Output:
int -- an integer between 0 and m*n - 1.
Examples:
>>> crt(1, 2, 3, 4)
10
>>> crt(4, 5, 10, 3)
14
>>> crt(-1, -1, 100, 101)
10099
"""
g, c, _ = xgcd(m, n)
assert g == 1, "m and n must be coprime."
return (a + (b-a)*c*m) % (m*n)
##################################################
## Computation of Powers
##################################################
def powermod(a, m, n):
"""
The m-th power of a modulo n.
Input:
a -- an integer
m -- a nonnegative integer
n -- a positive integer
Output:
int -- an integer between 0 and n-1
Examples:
>>> powermod(2,25,30)
2
>>> powermod(19,12345,100)
99
"""
assert m >= 0, "m must be nonnegative." # (1)
assert n >= 1, "n must be positive." # (2)
ans = 1
apow = a
while m != 0:
if m%2 != 0:
ans = (ans * apow) % n # (3)
apow = (apow * apow) % n # (4)
m /= 2
return ans % n
##################################################
## Finding a Primitive Root
##################################################
def primitive_root(p):
"""
Returns first primitive root modulo the prime p.
(If p is not prime, this return value of this function
is not meaningful.)
Input:
p -- an integer that is assumed prime
Output:
int -- a primitive root modulo p
Examples:
>>> primitive_root(7)
3
>>> primitive_root(389)
2
>>> primitive_root(5881)
31
"""
if p == 2: return 1
F = factor(p-1)
a = 2
while a < p:
generates = True
for q, _ in F:
if powermod(a, (p-1)/q, p) == 1:
generates = False
break
if generates: return a
a += 1
assert False, "p must be prime."
##################################################
## Determining Whether a Number is Prime
##################################################
def is_pseudoprime(n, bases = [2,3,5,7]):
"""
Returns True if n is a pseudoprime to the given bases,
in the sense that n>1 and b**(n-1) = 1 (mod n) for each
elements b of bases, with b not a multiple of n, and
False otherwise.
Input:
n -- an integer
bases -- a list of integers
Output:
bool
Examples:
>>> is_pseudoprime(91)
False
>>> is_pseudoprime(97)
True
>>> is_pseudoprime(1)
False
>>> is_pseudoprime(-2)
True
>>> s = [x for x in range(10000) if is_pseudoprime(x)]
>>> t = primes(10000)
>>> s == t
True
>>> is_pseudoprime(29341) # first non-prime pseudoprime
True
>>> factor(29341)
[(13, 1), (37, 1), (61, 1)]
"""
if n < 0: n = -n
if n <= 1: return False
for b in bases:
if b%n != 0 and powermod(b, n-1, n) != 1:
return False
return True
def miller_rabin(n, num_trials=4):
"""
True if n is likely prime, and False if n
is definitely not prime. Increasing num_trials
increases the probability of correctness.
(One can prove that the probability that this
function returns True when it should return
False is at most (1/4)**num_trials.)
Input:
n -- an integer
num_trials -- the number of trials with the
primality test.
Output:
bool -- whether or not n is probably prime.
Examples:
>>> miller_rabin(91)
False #rand
>>> miller_rabin(97)
True #rand
>>> s = [x for x in range(1000) if miller_rabin(x, 1)]
>>> t = primes(1000)
>>> print len(s), len(t) # so 1 in 25 wrong
175 168 #rand
>>> s = [x for x in range(1000) if miller_rabin(x)]
>>> s == t
True #rand
"""
if n < 0: n = -n
if n in [2,3]: return True
if n <= 4: return False
m = n - 1
k = 0
while m%2 == 0:
k += 1; m /= 2
# Now n - 1 = (2**k) * m with m odd
for i in range(num_trials):
a = randrange(2,n-1) # (1)
apow = powermod(a, m, n)
if not (apow in [1, n-1]):
some_minus_one = False
for r in range(k-1): # (2)
apow = (apow**2)%n
if apow == n-1:
some_minus_one = True
break # (3)
if (apow in [1, n-1]) or some_minus_one:
prob_prime = True
else:
return False
return True
##################################################
## The Diffie-Hellman Key Exchange
##################################################
def random_prime(num_digits, is_prime = miller_rabin):
"""
Returns a random prime with num_digits digits.
Input:
num_digits -- a positive integer
is_prime -- (optional argment)
a function of one argument n that
returns either True if n is (probably)
prime and False otherwise.
Output:
int -- an integer
Examples:
>>> random_prime(10)
8599796717L #rand
>>> random_prime(40)
1311696770583281776596904119734399028761L #rand
"""
n = randrange(10**(num_digits-1), 10**num_digits)
if n%2 == 0: n += 1
while not is_prime(n): n += 2
return n
def dh_init(p):
"""
Generates and returns a random positive
integer n < p and the power 2^n (mod p).
Input:
p -- an integer that is prime
Output:
int -- a positive integer < p, a secret
int -- 2^n (mod p), send to other user
Examples:
>>> p = random_prime(20)
>>> dh_init(p)
(15299007531923218813L, 4715333264598442112L) #rand
"""
n = randrange(2,p)
return n, powermod(2,n,p)
def dh_secret(p, n, mpow):
"""
Computes the shared Diffie-Hellman secret key.
Input:
p -- an integer that is prime
n -- an integer: output by dh_init for this user
mpow-- an integer: output by dh_init for other user
Output:
int -- the shared secret key.
Examples:
>>> p = random_prime(20)
>>> n, npow = dh_init(p)
>>> m, mpow = dh_init(p)
>>> dh_secret(p, n, mpow)
15695503407570180188L #rand
>>> dh_secret(p, m, npow)
15695503407570180188L #rand
"""
return powermod(mpow,n,p)
##################################################
## Encoding Strings as Lists of Integers
##################################################
def str_to_numlist(s, bound):
"""
Returns a sequence of integers between 0 and bound-1
that encodes the string s. Randomization is included,
so the same string is very likely to encode differently
each time this function is called.
Input:
s -- a string
bound -- an integer >= 256
Output:
list -- encoding of s as a list of integers
Examples:
>>> str_to_numlist("Run!", 1000)
[82, 117, 110, 33] #rand
>>> str_to_numlist("TOP SECRET", 10**20)
[4995371940984439512L, 92656709616492L] #rand
"""
assert bound >= 256, "bound must be at least 256."
n = int(log(bound) / log(256)) # (1)
salt = min(int(n/8) + 1, n-1) # (2)
i = 0; v = []
while i < len(s): # (3)
c = 0; pow = 1
for j in range(n): # (4)
if j < salt:
c += randrange(1,256)*pow # (5)
else:
if i >= len(s): break
c += ord(s[i])*pow # (6)
i += 1
pow *= 256
v.append(c)
return v
def numlist_to_str(v, bound):
"""
Returns the string that the sequence v of
integers encodes.
Input:
v -- list of integers between 0 and bound-1
bound -- an integer >= 256
Output:
str -- decoding of v as a string
Examples:
>>> print numlist_to_str([82, 117, 110, 33], 1000)
Run!
>>> x = str_to_numlist("TOP SECRET MESSAGE", 10**20)
>>> print numlist_to_str(x, 10**20)
TOP SECRET MESSAGE
"""
assert bound >= 256, "bound must be at least 256."
n = int(log(bound) / log(256))
s = ""
salt = min(int(n/8) + 1, n-1)
for x in v:
for j in range(n):
y = x%256
if y > 0 and j >= salt:
s += chr(y)
x /= 256
return s
##################################################
## The RSA Cryptosystem
##################################################
def rsa_init(p, q):
"""
Returns defining parameters (e, d, n) for the RSA
cryptosystem defined by primes p and q. The
primes p and q may be computed using the
random_prime functions.
Input:
p -- a prime integer
q -- a prime integer
Output:
Let m be (p-1)*(q-1).
e -- an encryption key, which is a randomly
chosen integer between 2 and m-1
d -- the inverse of e modulo eulerphi(p*q),
as an integer between 2 and m-1
n -- the product p*q.
Examples:
>>> p = random_prime(20); q = random_prime(20)
>>> print p, q
37999414403893878907L 25910385856444296437L #rand
>>> e, d, n = rsa_init(p, q)
>>> e
5 #rand
>>> d
787663591619054108576589014764921103213L #rand
>>> n
984579489523817635784646068716489554359L #rand
"""
m = (p-1)*(q-1)
e = 3
while gcd(e, m) != 1: e += 1
d = inversemod(e, m)
return e, d, p*q
def rsa_encrypt(plain_text, e, n):
"""
Encrypt plain_text using the encrypt
exponent e and modulus n.
Input:
plain_text -- arbitrary string
e -- an integer, the encryption exponent
n -- an integer, the modulus
Output:
str -- the encrypted cipher text
Examples:
>>> e = 1413636032234706267861856804566528506075
>>> n = 2109029637390047474920932660992586706589
>>> rsa_encrypt("Run Nikita!", e, n)
[78151883112572478169375308975376279129L] #rand
>>> rsa_encrypt("Run Nikita!", e, n)
[1136438061748322881798487546474756875373L] #rand
"""
plain = str_to_numlist(plain_text, n)
return [powermod(x, e, n) for x in plain]
def rsa_decrypt(cipher, d, n):
"""
Decrypt the cipher_text using the decryption
exponent d and modulus n.
Input:
cipher_text -- list of integers output
by rsa_encrypt
Output:
str -- the unencrypted plain text
Examples:
>>> d = 938164637865370078346033914094246201579
>>> n = 2109029637390047474920932660992586706589
>>> msg1 = [1071099761433836971832061585353925961069]
>>> msg2 = [1336506586627416245118258421225335020977]
>>> rsa_decrypt(msg1, d, n)
'Run Nikita!'
>>> rsa_decrypt(msg2, d, n)
'Run Nikita!'
"""
plain = [powermod(x, d, n) for x in cipher]
return numlist_to_str(plain, n)
##################################################
## Computing the Legendre Symbol
##################################################
def legendre(a, p):
"""
Returns the Legendre symbol a over p, where
p is an odd prime.
Input:
a -- an integer
p -- an odd prime (primality not checked)
Output:
int: -1 if a is not a square mod p,
0 if gcd(a,p) is not 1
1 if a is a square mod p.
Examples:
>>> legendre(2, 5)
-1
>>> legendre(3, 3)
0
>>> legendre(7, 2003)
-1
"""
assert p%2 == 1, "p must be an odd prime."
b = powermod(a, (p-1)/2, p)
if b == 1: return 1
elif b == p-1: return -1
return 0
##################################################
## In this section we implement the algorithm
##################################################
def sqrtmod(a, p):
"""
Returns a square root of a modulo p.
Input:
a -- an integer that is a perfect
square modulo p (this is checked)
p -- a prime
Output:
int -- a square root of a, as an integer
between 0 and p-1.
Examples:
>>> sqrtmod(4, 5) # p == 1 (mod 4)
3 #rand
>>> sqrtmod(13, 23) # p == 3 (mod 4)
6 #rand
>>> sqrtmod(997, 7304723089) # p == 1 (mod 4)
761044645L #rand
"""
a %= p
if p == 2: return a
assert legendre(a, p) == 1, "a must be a square mod p."
if p%4 == 3: return powermod(a, (p+1)/4, p)
def mul(x, y): # multiplication in R # (1)
return ((x[0]*y[0] + a*y[1]*x[1]) % p, \
(x[0]*y[1] + x[1]*y[0]) % p)
def pow(x, n): # exponentiation in R # (2)
ans = (1,0)
xpow = x
while n != 0:
if n%2 != 0: ans = mul(ans, xpow)
xpow = mul(xpow, xpow)
n /= 2
return ans
while True:
z = randrange(2,p)
u, v = pow((1,z), (p-1)/2)
if v != 0:
vinv = inversemod(v, p)
for x in [-u*vinv, (1-u)*vinv, (-1-u)*vinv]:
if (x*x)%p == a: return x%p
assert False, "Bug in sqrtmod."
##################################################
## Continued Fractions
##################################################
def convergents(v):
"""
Returns the partial convergents of the continued
fraction v.
Input:
v -- list of integers [a0, a1, a2, ..., am]
Output:
list -- list [(p0,q0), (p1,q1), ...]
of pairs (pm,qm) such that the mth
convergent of v is pm/qm.
Examples:
>>> convergents([1, 2])
[(1, 1), (3, 2)]
>>> convergents([3, 7, 15, 1, 292])
[(3, 1), (22, 7), (333, 106), (355, 113), (103993, 33102)]
"""
w = [(0,1), (1,0)]
for n in range(len(v)):
pn = v[n]*w[n+1][0] + w[n][0]
qn = v[n]*w[n+1][1] + w[n][1]
w.append((pn, qn))
del w[0]; del w[0] # remove first entries of w
return w
def contfrac_rat(numer, denom):
"""
Returns the continued fraction of the rational
number numer/denom.
Input:
numer -- an integer
denom -- a positive integer coprime to num
Output
list -- the continued fraction [a0, a1, ..., am]
of the rational number num/denom.
Examples:
>>> contfrac_rat(3, 2)
[1, 2]
>>> contfrac_rat(103993, 33102)
[3, 7, 15, 1, 292]
"""
assert denom > 0, "denom must be positive"
a = numer; b = denom
v = []
while b != 0:
v.append(a/b)
(a, b) = (b, a%b)
return v
def contfrac_float(x):
"""
Returns the continued fraction of the floating
point number x, computed using the continued
fraction procedure, and the sequence of partial
convergents.
Input:
x -- a floating point number (decimal)
Output:
list -- the continued fraction [a0, a1, ...]
obtained by applying the continued
fraction procedure to x to the
precision of this computer.
list -- the list [(p0,q0), (p1,q1), ...]
of pairs (pm,qm) such that the mth
convergent of continued fraction
is pm/qm.
Examples:
>>> v, w = contfrac_float(3.14159); print v
[3, 7, 15, 1, 25, 1, 7, 4]
>>> v, w = contfrac_float(2.718); print v
[2, 1, 2, 1, 1, 4, 1, 12]
>>> contfrac_float(0.3)
([0, 3, 2, 1], [(0, 1), (1, 3), (2, 7), (3, 10)])
"""
v = []
w = [(0,1), (1,0)] # keep track of convergents
start = x
while True:
a = int(x) # (1)
v.append(a)
n = len(v)-1
pn = v[n]*w[n+1][0] + w[n][0]
qn = v[n]*w[n+1][1] + w[n][1]
w.append((pn, qn))
x -= a
if abs(start - float(pn)/float(qn)) == 0: # (2)
del w[0]; del w[0] # (3)
return v, w
x = 1/x
def sum_of_two_squares(p):
"""
Uses continued fractions to efficiently compute
a representation of the prime p as a sum of
two squares. The prime p must be 1 modulo 4.
Input:
p -- a prime congruent 1 modulo 4.
Output:
integers a, b such that p is a*a + b*b
Examples:
>>> sum_of_two_squares(5)
(1, 2)
>>> sum_of_two_squares(389)
(10, 17)
>>> sum_of_two_squares(86295641057493119033)
(789006548L, 9255976973L)
"""
assert p%4 == 1, "p must be 1 modulo 4"
r = sqrtmod(-1, p) # (1)
v = contfrac_rat(-r, p) # (2)
n = int(sqrt(p))
for a, b in convergents(v): # (3)
c = r*b + p*a # (4)
if -n <= c and c <= n: return (abs(b),abs(c))
assert False, "Bug in sum_of_two_squares." # (5)
##################################################
## Arithmetic
##################################################
def ellcurve_add(E, P1, P2):
"""
Returns the sum of P1 and P2 on the elliptic
curve E.
Input:
E -- an elliptic curve over Z/pZ, given by a
triple of integers (a, b, p), with p odd.
P1 --a pair of integers (x, y) or the
string "Identity".
P2 -- same type as P1
Output:
R -- same type as P1
Examples:
>>> E = (1, 0, 7) # y**2 = x**3 + x over Z/7Z
>>> P1 = (1, 3); P2 = (3, 3)
>>> ellcurve_add(E, P1, P2)
(3, 4)
>>> ellcurve_add(E, P1, (1, 4))
'Identity'
>>> ellcurve_add(E, "Identity", P2)
(3, 3)
"""
a, b, p = E
assert p > 2, "p must be odd."
if P1 == "Identity": return P2
if P2 == "Identity": return P1
x1, y1 = P1; x2, y2 = P2
x1 %= p; y1 %= p; x2 %= p; y2 %= p
if x1 == x2 and y1 == p-y2: return "Identity"
if P1 == P2:
if y1 == 0: return "Identity"
lam = (3*x1**2+a) * inversemod(2*y1,p)
else:
lam = (y1 - y2) * inversemod(x1 - x2, p)
x3 = lam**2 - x1 - x2
y3 = -lam*x3 - y1 + lam*x1
return (x3%p, y3%p)
def ellcurve_mul(E, m, P):
"""
Returns the multiple m*P of the point P on
the elliptic curve E.
Input:
E -- an elliptic curve over Z/pZ, given by a
triple (a, b, p).
m -- an integer
P -- a pair of integers (x, y) or the
string "Identity"
Output:
A pair of integers or the string "Identity".
Examples:
>>> E = (1, 0, 7)
>>> P = (1, 3)
>>> ellcurve_mul(E, 5, P)
(1, 3)
>>> ellcurve_mul(E, 9999, P)
(1, 4)
"""
assert m >= 0, "m must be nonnegative."
power = P
mP = "Identity"
while m != 0:
if m%2 != 0: mP = ellcurve_add(E, mP, power)
power = ellcurve_add(E, power, power)
m /= 2
return mP
##################################################
## Integer Factorization
##################################################
def lcm_to(B):
"""
Returns the least common multiple of all
integers up to B.
Input:
B -- an integer
Output:
an integer
Examples:
>>> lcm_to(5)
60
>>> lcm_to(20)
232792560
>>> lcm_to(100)
69720375229712477164533808935312303556800L
"""
ans = 1
logB = log(B)
for p in primes(B):
ans *= p**int(logB/log(p))
return ans
def pollard(N, m):
"""
Use Pollard's (p-1)-method to try to find a
nontrivial divisor of N.
Input:
N -- a positive integer
m -- a positive integer, the least common
multiple of the integers up to some
bound, computed using lcm_to.
Output:
int -- an integer divisor of n
Examples:
>>> pollard(5917, lcm_to(5))
61
>>> pollard(779167, lcm_to(5))
779167
>>> pollard(779167, lcm_to(15))
2003L
>>> pollard(187, lcm_to(15))
11
>>> n = random_prime(5)*random_prime(5)*random_prime(5)
>>> pollard(n, lcm_to(100))
315873129119929L #rand
>>> pollard(n, lcm_to(1000))
3672986071L #rand
"""
for a in [2, 3]:
x = powermod(a, m, N) - 1
g = gcd(x, N)
if g != 1 and g != N:
return g
return N
def randcurve(p):
"""
Construct a somewhat random elliptic curve
over Z/pZ and a random point on that curve.
Input:
p -- a positive integer
Output:
tuple -- a triple E = (a, b, p)
P -- a tuple (x,y) on E
Examples:
>>> p = random_prime(20); p
17758176404715800329L #rand
>>> E, P = randcurve(p)
>>> print E
(15299007531923218813L, 1, 17758176404715800329L) #rand
>>> print P
(0, 1)
"""
assert p > 2, "p must be > 2."
a = randrange(p)
while gcd(4*a**3 + 27, p) != 1:
a = randrange(p)
return (a, 1, p), (0,1)
def elliptic_curve_method(N, m, tries=5):
"""
Use the elliptic curve method to try to find a
nontrivial divisor of N.