44Source: https://en.wikipedia.org/wiki/Shor%27s_algorithm
55"""
66
7- import random
87import math
9- from typing import Tuple , Union
8+ import random
9+ from typing import Any
1010
1111
1212def is_prime (n : int ) -> bool :
@@ -24,11 +24,8 @@ def is_prime(n: int) -> bool:
2424 return True
2525 if n % 2 == 0 :
2626 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 ))
3229
3330
3431def modexp (a : int , b : int , m : int ) -> int :
@@ -48,7 +45,7 @@ def modexp(a: int, b: int, m: int) -> int:
4845 return result
4946
5047
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 ]:
5249 """
5350 Classical approximation of Shor's Algorithm to factor a number.
5451
@@ -61,36 +58,36 @@ def shor_classical(N: int, max_attempts: int = 10) -> Union[str, Tuple[int, int]
6158 >>> shor_classical(13) # Prime
6259 'No factors: 13 is prime'
6360 """
64- if N <= 1 :
61+ if n <= 1 :
6562 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"
7067
7168 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 )
7471 if g > 1 :
75- return g , N // g
72+ return g , n // g
7673
7774 r = 1
78- while r < N :
79- if modexp (a , r , N ) == 1 :
75+ while r < n :
76+ if modexp (a , r , n ) == 1 :
8077 break
8178 r += 1
8279 else :
8380 continue
8481
8582 if r % 2 != 0 :
8683 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 :
8986 continue
9087
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 ):
9491 return factor1 , factor2
9592
9693 return "Failure: try more attempts"
0 commit comments