📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / source-code / Pseudocode / Calculate-Legendre / calculate_legendre.py
132930 viewsLicense: OTHER
#!/usr/bin/env python1# -*- coding: utf-8 -*-234def is_prime(a):5"""6Check if `a` is a prime number.78Parameters9----------10a : int, a >= 211"""12return all(a % i for i in xrange(2, a))131415# http://stackoverflow.com/a/14793082/56276916def factorize(n):17factors = []1819p = 220while True:21# while we can divide by smaller number, do so22while(n % p == 0 and n > 0):23factors.append(p)24n = n / p25p += 1 # p is not necessary prime, but n%p == 0 only for prime numbers26if p > n / p:27break28if n > 1:29factors.append(n)30return factors313233def calculate_legendre(a, p):34"""35Calculate the legendre symbol (a, p) with p is prime.36The result is either -1, 0 or 13738>>> calculate_legendre(3, 29)39-140>>> calculate_legendre(111, 41) # Beispiel aus dem Skript, S. 11441-142>>> calculate_legendre(113, 41) # Beispiel aus dem Skript, S. 11443144>>> calculate_legendre(2, 31)45146>>> calculate_legendre(5, 31)4714849# http://math.stackexchange.com/q/221223/687650>>> calculate_legendre(150, 1009)5115253# http://math.stackexchange.com/q/221223/687654>>> calculate_legendre(25, 1009)5515657# http://math.stackexchange.com/q/221223/687658>>> calculate_legendre(2, 1009)5916061# http://math.stackexchange.com/q/221223/687662>>> calculate_legendre(3, 1009)63164"""65if a >= p or a < 0:66return calculate_legendre(a % p, p)67elif a == 0 or a == 1:68return a69elif a == 2:70if p % 8 == 1 or p % 8 == 7:71return 172else:73return -174elif a == p-1:75if p % 4 == 1:76return 177else:78return -179elif not is_prime(a):80factors = factorize(a)81product = 182for pi in factors:83product *= calculate_legendre(pi, p)84return product85else:86if ((p-1)/2) % 2 == 0 or ((a-1)/2) % 2 == 0:87return calculate_legendre(p, a)88else:89return (-1)*calculate_legendre(p, a)9091if __name__ == "__main__":92import doctest93doctest.testmod()949596