4
4
Source: https://en.wikipedia.org/wiki/Shor%27s_algorithm
5
5
"""
6
6
7
- import random
8
7
import math
9
- from typing import Tuple , Union
8
+ import random
9
+ from typing import Any
10
10
11
11
12
12
def is_prime (n : int ) -> bool :
@@ -24,11 +24,8 @@ def is_prime(n: int) -> bool:
24
24
return True
25
25
if n % 2 == 0 :
26
26
return False
27
- r = int (math .isqrt (n ))
28
- for i in range (3 , r + 1 , 2 ):
29
- if n % i == 0 :
30
- return False
31
- return True
27
+ r = math .isqrt (n )
28
+ return all (n % i != 0 for i in range (3 , r + 1 , 2 ))
32
29
33
30
34
31
def modexp (a : int , b : int , m : int ) -> int :
@@ -48,7 +45,7 @@ def modexp(a: int, b: int, m: int) -> int:
48
45
return result
49
46
50
47
51
- def shor_classical (N : int , max_attempts : int = 10 ) -> Union [ str , Tuple [int , int ] ]:
48
+ def shor_classical (n : int , max_attempts : int = 10 ) -> str | tuple [int , int ]:
52
49
"""
53
50
Classical approximation of Shor's Algorithm to factor a number.
54
51
@@ -61,36 +58,36 @@ def shor_classical(N: int, max_attempts: int = 10) -> Union[str, Tuple[int, int]
61
58
>>> shor_classical(13) # Prime
62
59
'No factors: 13 is prime'
63
60
"""
64
- if N <= 1 :
61
+ if n <= 1 :
65
62
return "Failure: input must be > 1"
66
- if N % 2 == 0 :
67
- return 2 , N // 2
68
- if is_prime (N ):
69
- return f"No factors: { N } is prime"
63
+ if n % 2 == 0 :
64
+ return 2 , n // 2
65
+ if is_prime (n ):
66
+ return f"No factors: { n } is prime"
70
67
71
68
for _ in range (max_attempts ):
72
- a = random .randrange (2 , N - 1 )
73
- g = math .gcd (a , N )
69
+ a = random .randrange (2 , n - 1 )
70
+ g = math .gcd (a , n )
74
71
if g > 1 :
75
- return g , N // g
72
+ return g , n // g
76
73
77
74
r = 1
78
- while r < N :
79
- if modexp (a , r , N ) == 1 :
75
+ while r < n :
76
+ if modexp (a , r , n ) == 1 :
80
77
break
81
78
r += 1
82
79
else :
83
80
continue
84
81
85
82
if r % 2 != 0 :
86
83
continue
87
- x = modexp (a , r // 2 , N )
88
- if x == N - 1 :
84
+ x = modexp (a , r // 2 , n )
85
+ if x == n - 1 :
89
86
continue
90
87
91
- factor1 = math .gcd (x - 1 , N )
92
- factor2 = math .gcd (x + 1 , N )
93
- if factor1 not in (1 , N ) and factor2 not in (1 , N ):
88
+ factor1 = math .gcd (x - 1 , n )
89
+ factor2 = math .gcd (x + 1 , n )
90
+ if factor1 not in (1 , n ) and factor2 not in (1 , n ):
94
91
return factor1 , factor2
95
92
96
93
return "Failure: try more attempts"
0 commit comments