Shor’s Factorization Algorithm:
- Shor’s Factorization Algorithm is proposed by Peter Shor.
- It suggests that quantum mechanics allows the factorization to be performed in polynomial time, rather than exponential time achieved after using classical algorithms.
- This could have a drastic impact on the field of data security, a concept based on the prime factorization of large numbers.
- Many polynomial-time algorithms for integer multiplication (e.g., Euclid’s Algorithm) do exist, but no polynomial-time algorithm for factorization exists.
- So, Shor came up with an algorithm i.e. Shor’s Factorization Algorithm, an algorithm for factorizing non-prime integers N of L bits.
- Quantum algorithms are far much better than classical algorithms because they are based on Quantum Fourier Transform.
- Run time on the classical computer is O[exp (L1/3(log L)2/3)] but that on the quantum computer is O(L3).
- So, Shor’s Algorithm in principle, shows that a quantum computer is capable of factoring very large numbers in polynomial time.
Shor’s Algorithm depends on:
The Algorithm stands as:
Given an odd composite number N, find an integer d, strictly between 1 and N, that divides N.
Shor’s Algorithm consists of the following two parts:
- Conversion of the problem of factorizing to the problem of finding the period. This part can be implemented with classical means.
- Finding the period or Quantum period finding using the Quantum Fourier Transform, and is responsible for quantum speedup, and utilizes quantum parallelism.
In Shor’s Algorithm, the Input is Non-prime number N and the Output is Non-trivial factor of N
INPUT (N) ---> SHOR'S ALGORITHM ---> OUTPUT (Non-trivial factor of N)
Algorithm: It contains a few steps, at only step 2 the use of quantum computers is required.
- Choose any random number let say r, such that r < N so that they are co-primes of each other.
- A quantum computer is used to determine the unknown period p of the function fr, N (x) = rx mod N.
- If p is an odd integer, then go back to Step 1. Else move to the next step.
- Since p is an even integer so, (rp/2 - 1)(rp/2 + 1) = rp - 1 = 0 mod N.
- Now, if the value of rp/2 + 1 = 0 mod N, go back to Step 1.
- If the value of rp/2 + 1 != 0 mod N, Else move to the next step.
- Compute d = gcd(rp/2-1, N).
- The answer required is ‘d’.
Classical part (The order finding problem):
This is the classical part of order finding problem. Given that x and N, such that x<N and gcd(x, N) = 1. The order of x is the least positive integer, y such that xy = 1(mod N).
- A random number n is picked, such that n < N. Compute gcd(n, N).
- This can be done using the Euclid Algorithm.
- If gcd(n, N) != 1, then there is a non-trivial factor of N.If (x+p) = nx + p mod N = nxmod N = f(x).
- If r is odd, then go back to Step 1.
- If np/2 = -1(mod N), then go back to Step 1.
- The gcd(np/2 +/- 1, N) is a non-trivial factor of N.
Quantum part:
This is the quantum order finding part. Choose a power of 2, then
Q = 2L such that N2 <= Q <= 2N2
And consider f = {0, 1, 2, …, Q-1}
Where, f(y)=1/(Q)1/2 ∑x=0Q-1I f(x) I wxy and w = exp(2π i/Q), i.e. Qth root of unity.
- Let's perform Shor's Algorithm using an example: To factor an odd integer N (let N = 17).
- Choose an integer Q such that N2 <= Q ≤ 2 N2 ( lets Q = 324).
- Then, randomly choose any integer n such that gcd(n, N)=1, (let us choose the integer be n=7).
- Then create two quantum registers (these registers should be entangled so that the collapse of the input registered corresponds to the collapse of the output register)
- Input Register: must be containing enough qubits to represent numbers as large as Q-1.(i.e., up to 323, so we need 9 qubits).
- Output Register: must be containing enough qubits to represent numbers as large as (N - 1). (i.e., up to 16, so we require 4 qubits).
Code :
#include <iostream>
#include <vector>
#include <cmath>
#include <complex>
#include <qiskit/providers/ibmq/ibmqfactory.hpp>
#include <qiskit/aqua/algorithms/shor/shor.hpp>
using namespace std;
using namespace qiskit;
int main() {
// Enter your API token here
string apiToken = "ENTER_API_TOKEN_HERE";
// Enable IBM Quantum Experience account
IBMQ::enable_account(apiToken);
// Get the IBM Quantum provider
auto provider = IBMQ::get_provider("ibm-q");
// Specifies the quantum device
auto backend = provider.get_backend("ibmq_qasm_simulator");
cout << "\n Shors Algorithm" << endl;
cout << "--------------------" << endl;
cout << "\nExecuting...\n" << endl;
// Function to run Shor's algorithm
// where 35 is the integer to be factored
auto factors = shor(35);
auto result_dict = factors.run(QuantumInstance(
backend, 1, false
));
// Get factors from results
vector<complex<double>> result = result_dict["factors"];
cout << "Result: ";
for (const auto &factor : result) {
cout << factor << " ";
}
cout << "\nPress any key to close" << endl;
cin.get();
return 0;
}
//Java code to implement Shor’s Factorization Algorithm
import java.io.*;
import com.qiskit.providers.ibmq.IBMQ;
import com.qiskit.providers.ibmq.runtime.IBMRuntime;
import com.qiskit.providers.ibmq.runtime.QiskitRuntime;
import com.qiskit.providers.ibmq.runtime.RunConfig;
import com.qiskit.providers.ibmq.runtime.RunConfigBuilder;
import com.qiskit.providers.ibmq.runtime.RunResult;
import com.qiskit.providers.ibmq.runtime.RunResultData;
class GFG {
public static void main (String[] args) {
// Enter your API token here
String apiToken = "ENTER API TOKEN HERE";
// Enable IBM Quantum Experience account
IBMQ.enableAccount(apiToken);
// Get the IBM Quantum provider
IBMRuntime ibmRuntime = IBMQ.getRuntime();
// Specifies the quantum device
String backendName = "ibmq_qasm_simulator";
// Print a message
System.out.println("\n Shor's Algorithm");
System.out.println("--------------------");
System.out.println("\nExecuting...\n");
// Function to run Shor's algorithm
// where 35 is the integer to be factored
int numberToFactorize = 35;
RunConfig runConfig = new RunConfigBuilder()
.backend(backendName)
.shots(1)
.build();
QiskitRuntime shorRuntime = ibmRuntime.run(
Shor.class.getName(),
RunConfig.class.getName(),
runConfig,
new int[]{numberToFactorize});
// Wait for the runtime to finish
shorRuntime.await();
// Get the result from the runtime
RunResult runResult = shorRuntime.getResult();
RunResultData resultData = runResult.getData();
// Get factors from results
Object[] result = (Object[]) resultData.get("factors");
// Print the result
System.out.println(result[0]);
// Print a message to close
System.out.println("\nPress any key to close");
}
}
// This code is contributed by Pranay Arora
from qiskit import IBMQ
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Shor
# Enter your API token here
IBMQ.enable_account('ENTER API TOKEN HERE')
provider = IBMQ.get_provider(hub='ibm-q')
# Specifies the quantum device
backend = provider.get_backend('ibmq_qasm_simulator')
print('\n Shors Algorithm')
print('--------------------')
print('\nExecuting...\n')
# Function to run Shor's algorithm
# where 35 is the integer to be factored
factors = Shor(35)
result_dict = factors.run(QuantumInstance(
backend, shots=1, skip_qobj_validation=False))
# Get factors from results
result = result_dict['factors']
print(result)
print('\nPress any key to close')
input()
using System;
using IBM.Quantum.IBMQ;
using IBM.Quantum.IBMQ.Runtime;
using IBM.Quantum.IBMQ.Runtime.Jobs;
using IBM.Quantum.IBMQ.Runtime.Utils;
using System.Threading.Tasks;
class GFG
{
static async Task Main(string[] args)
{
// Enter your API token here
string apiToken = "ENTER API TOKEN HERE";
// Enable IBM Quantum Experience account
IBMQ.IBQAccountToken = apiToken;
// Get the IBM Quantum provider
IBMRuntime ibmRuntime = IBMQ.GetIBMRuntime();
// Specifies the quantum device
string backendName = "ibmq_qasm_simulator";
// Print a message
Console.WriteLine("\n Shor's Algorithm");
Console.WriteLine("--------------------");
Console.WriteLine("\nExecuting...\n");
// Function to run Shor's algorithm
// where 35 is the integer to be factored
int numberToFactorize = 35;
RunConfig runConfig = new RunConfigBuilder()
.Backend(backendName)
.Shots(1)
.Build();
QiskitRuntime shorRuntime = await ibmRuntime.RunAsync(
typeof(Shor).FullName,
typeof(RunConfig).FullName,
runConfig,
new object[] { numberToFactorize });
// Wait for the runtime to finish
await shorRuntime.AwaitCompletionAsync();
// Get the result from the runtime
RunResult runResult = shorRuntime.GetResult();
RunResultData resultData = runResult.GetData();
// Get factors from results
object[] result = (object[])resultData.Get("factors");
// Print the result
Console.WriteLine(result[0]);
// Print a message to close
Console.WriteLine("\nPress any key to close");
}
}
// Import necessary libraries
const { IBMQ } = require('ibm-q');
const { Shor } = require('qiskit.algorithms');
// Function to run Shor's algorithm
async function runShorsAlgorithm() {
try {
// Enter your API token here
const apiToken = 'ENTER API TOKEN HERE';
// Enable IBM Quantum Experience account
await IBMQ.enableAccount(apiToken);
// Get the IBM Quantum provider
const ibmRuntime = IBMQ.getRuntime();
// Specifies the quantum device
const backendName = 'ibmq_qasm_simulator';
// Print a message
console.log('\n Shor\'s Algorithm');
console.log('--------------------');
console.log('\nExecuting...\n');
// Define the number to factorize
const numberToFactorize = 35;
// Define run configuration
const runConfig = {
backend: backendName,
shots: 1
};
// Run Shor's algorithm
const shorRuntime = await ibmRuntime.run(
Shor,
runConfig,
[numberToFactorize]
);
// Wait for the runtime to finish
await shorRuntime.await();
// Get the result from the runtime
const runResult = await shorRuntime.getResult();
const resultData = runResult.getData();
// Get factors from results
const factors = resultData.get('factors');
// Print the result
console.log(factors[0]);
// Print a message to close
console.log('\nPress any key to close');
} catch (error) {
console.error('Error:', error);
}
}
// Run the Shor's algorithm function
runShorsAlgorithm();
Output :
Shors Algorithm
- - - - - - - - - - - - -
Executing...
[[5,7]]
Press any key to close
Output for the code above showing the factors 5 and 7 for N=35.
Time Complexity : O(1)
Space Complexity : O(1)