Calculate the Jacobi symbol. The Jacobi symbol is a generalization of the Legendre symbol, which can be used to simplify computations involving quadratic residues. The Jacobi symbol is used in primality tests, like the Solovay-Strassen test, because it helps determine if an integer
(random_a: int, number: int)
| 13 | |
| 14 | |
| 15 | def jacobi_symbol(random_a: int, number: int) -> int: |
| 16 | """ |
| 17 | Calculate the Jacobi symbol. The Jacobi symbol is a generalization |
| 18 | of the Legendre symbol, which can be used to simplify computations involving |
| 19 | quadratic residues. The Jacobi symbol is used in primality tests, like the |
| 20 | Solovay-Strassen test, because it helps determine if an integer is a |
| 21 | quadratic residue modulo a given modulus, providing valuable information |
| 22 | about the number's potential primality or compositeness. |
| 23 | |
| 24 | Parameters: |
| 25 | random_a: A randomly chosen integer from 2 to n-2 (inclusive) |
| 26 | number: The number that is tested for primality |
| 27 | |
| 28 | Returns: |
| 29 | jacobi_symbol: The Jacobi symbol is a mathematical function |
| 30 | used to determine whether an integer is a quadratic residue modulo |
| 31 | another integer (usually prime) or not. |
| 32 | |
| 33 | >>> jacobi_symbol(2, 13) |
| 34 | -1 |
| 35 | >>> jacobi_symbol(5, 19) |
| 36 | 1 |
| 37 | >>> jacobi_symbol(7, 14) |
| 38 | 0 |
| 39 | """ |
| 40 | |
| 41 | if random_a in (0, 1): |
| 42 | return random_a |
| 43 | |
| 44 | random_a %= number |
| 45 | t = 1 |
| 46 | |
| 47 | while random_a != 0: |
| 48 | while random_a % 2 == 0: |
| 49 | random_a //= 2 |
| 50 | r = number % 8 |
| 51 | if r in (3, 5): |
| 52 | t = -t |
| 53 | |
| 54 | random_a, number = number, random_a |
| 55 | |
| 56 | if random_a % 4 == number % 4 == 3: |
| 57 | t = -t |
| 58 | |
| 59 | random_a %= number |
| 60 | |
| 61 | return t if number == 1 else 0 |
| 62 | |
| 63 | |
| 64 | def solovay_strassen(number: int, iterations: int) -> bool: |