Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132930 views
License: OTHER
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
5
def is_prime(a):
6
"""
7
Check if `a` is a prime number.
8
9
Parameters
10
----------
11
a : int, a >= 2
12
"""
13
return all(a % i for i in xrange(2, a))
14
15
16
# http://stackoverflow.com/a/14793082/562769
17
def factorize(n):
18
factors = []
19
20
p = 2
21
while True:
22
# while we can divide by smaller number, do so
23
while(n % p == 0 and n > 0):
24
factors.append(p)
25
n = n / p
26
p += 1 # p is not necessary prime, but n%p == 0 only for prime numbers
27
if p > n / p:
28
break
29
if n > 1:
30
factors.append(n)
31
return factors
32
33
34
def calculate_legendre(a, p):
35
"""
36
Calculate the legendre symbol (a, p) with p is prime.
37
The result is either -1, 0 or 1
38
39
>>> calculate_legendre(3, 29)
40
-1
41
>>> calculate_legendre(111, 41) # Beispiel aus dem Skript, S. 114
42
-1
43
>>> calculate_legendre(113, 41) # Beispiel aus dem Skript, S. 114
44
1
45
>>> calculate_legendre(2, 31)
46
1
47
>>> calculate_legendre(5, 31)
48
1
49
50
# http://math.stackexchange.com/q/221223/6876
51
>>> calculate_legendre(150, 1009)
52
1
53
54
# http://math.stackexchange.com/q/221223/6876
55
>>> calculate_legendre(25, 1009)
56
1
57
58
# http://math.stackexchange.com/q/221223/6876
59
>>> calculate_legendre(2, 1009)
60
1
61
62
# http://math.stackexchange.com/q/221223/6876
63
>>> calculate_legendre(3, 1009)
64
1
65
"""
66
if a >= p or a < 0:
67
return calculate_legendre(a % p, p)
68
elif a == 0 or a == 1:
69
return a
70
elif a == 2:
71
if p % 8 == 1 or p % 8 == 7:
72
return 1
73
else:
74
return -1
75
elif a == p-1:
76
if p % 4 == 1:
77
return 1
78
else:
79
return -1
80
elif not is_prime(a):
81
factors = factorize(a)
82
product = 1
83
for pi in factors:
84
product *= calculate_legendre(pi, p)
85
return product
86
else:
87
if ((p-1)/2) % 2 == 0 or ((a-1)/2) % 2 == 0:
88
return calculate_legendre(p, a)
89
else:
90
return (-1)*calculate_legendre(p, a)
91
92
if __name__ == "__main__":
93
import doctest
94
doctest.testmod()
95
96