TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
#include <cassert>
#include <iostream>
#include <random>
#include <vector>
Go to the source code of this file.
Functions | |
template<typename T > | |
std::vector< T > | reverse_binary (T num) |
template<typename T > | |
T | modular_exponentiation (T base, const std::vector< T > &rev_binary_exponent, T mod) |
template<typename T > | |
bool | miller_test (T d, T num) |
template<typename T > | |
bool | miller_rabin_primality_test (T num, T repeats) |
void | tests () |
int | main () |
Copyright 2020
A basic implementation of Miller-Rabin primality test.
Definition in file miller_rabin.cpp.
int main | ( | void | ) |
Main function
Definition at line 183 of file miller_rabin.cpp.
bool miller_rabin_primality_test | ( | T | num, |
T | repeats ) |
Function that test (probabilistically) whether a given number is a prime based on the Miller-Rabin Primality Test.
num | number to be tested for primality. |
repeats | number of repetitions for the test to increase probability of correct result. |
\detail First we check whether the num input is less than 4, if so we can determine whether this is a prime or composite by checking for 2 and 3. Next we check whether this num is odd (as all primes greater than 2 are odd). Next we write our num in the following format \(num = 2^r \cdot d + 1\). After finding r and d for our input num, we use for loop repeat number of times inside which we check the miller conditions using the function miller_test. If miller_test returns false then the number is composite After the loop finishes completely without issuing a false return call, we can conclude that this number is probably prime.
Definition at line 125 of file miller_rabin.cpp.
bool miller_test | ( | T | d, |
T | num ) |
Function for testing the conditions that are satisfied when a number is prime.
d | number such that \(d \cdot 2^r = n - 1\) where \(n = num\) parameter and \(r \geq 1\) |
num | number being tested for primality. |
Definition at line 73 of file miller_rabin.cpp.
T modular_exponentiation | ( | T | base, |
const std::vector< T > & | rev_binary_exponent, | ||
T | mod ) |
Function for modular exponentiation. This function is an efficient modular exponentiation function. It can be used with any big integer library such as Boost multiprecision to give result any modular exponentiation problem relatively quickly.
base | number being raised to a power as integer |
rev_binary_exponent | reverse binary of the power the base is being raised to |
mod | modulo |
Definition at line 43 of file miller_rabin.cpp.
std::vector< T > reverse_binary | ( | T | num | ) |
Function to give a binary representation of a number in reverse order
num | integer number that we want to convert |
Definition at line 19 of file miller_rabin.cpp.
void tests | ( | ) |
Functions for testing the miller_rabin_primality_test() function with some assert statements.
Definition at line 157 of file miller_rabin.cpp.