1+ import math
2+ import random
3+
4+ """
5+ Shor Algorithm is one of the basic quantum computing algorithm
6+ that is used in breaking the RSA cryptography protocol, by finding the
7+ prime numbers that are used to create the public key value, n
8+
9+ In this implementation, I have used a very simple construct without
10+ the use of qiskit or cirq to help understand how Shor algorithm's
11+ idea actually works.
12+ """
13+ class Shor :
14+ def period_find (self , num : int , number : int ) -> int :
15+ """
16+ Find the period of a^x mod N.
17+
18+ >>> shor = Shor()
19+ >>> shor.period_find(2, 15)
20+ 4
21+ >>> shor.period_find(3, 7)
22+ 6
23+ """
24+ start :int = 1
25+ while pow (num , start , number ) != 1 :
26+ start += 1
27+ return start
28+
29+ def shor_algorithm (self , number :int ) -> list [int ]:
30+ """
31+ Run Shor's algorithm to factor a number.
32+ >>> shor = Shor()
33+ >>> random.seed(0)
34+ >>> factors = shor.shor_algorithm(15)
35+ >>> isinstance(factors, tuple) and len(factors) == 2
36+ True
37+ >>> factors
38+ (3, 5)
39+ """
40+ if number % 2 == 0 :
41+ return 2 , number // 2
42+ while True :
43+ random .seed (0 )
44+ num :int = random .randint (2 , number - 1 )
45+ gcd_number_num :int = math .gcd (number , num )
46+ if gcd_number_num > 1 :
47+ return gcd_number_num , number // gcd_number_num
48+
49+ result :int = self .period_find (num , number )
50+ if not result % 2 :
51+ start :int = pow (num , result // 2 , number )
52+ if start != number - 1 :
53+ p_value :int = math .gcd (start - 1 , number )
54+ q_value :int = math .gcd (start + 1 , number )
55+ if p_value > 1 and q_value > 1 :
56+ return p_value , q_value
57+
58+
59+ shor = Shor ()
60+ print (shor .shor_algorithm (15 ))
61+
62+
63+
64+
0 commit comments