TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
An algorithm to divide two numbers under modulo p Modular Division More...
#include <cassert>
#include <cstdint>
#include <iostream>
Go to the source code of this file.
Namespaces | |
namespace | math |
for assert | |
namespace | modular_division |
Functions for Modular Division implementation. | |
Functions | |
uint64_t | math::modular_division::power (uint64_t a, uint64_t b, uint64_t c) |
This function calculates a raised to exponent b under modulo c using modular exponentiation. | |
uint64_t | math::modular_division::mod_division (uint64_t a, uint64_t b, uint64_t p) |
This function calculates modular division. | |
static void | test () |
int | main (int argc, char *argv[]) |
Main function. | |
An algorithm to divide two numbers under modulo p Modular Division
To calculate division of two numbers under modulo p Modulo operator is not distributive under division, therefore we first have to calculate the inverse of divisor using Fermat's little theorem Now, we can multiply the dividend with the inverse of divisor and modulo is distributive over multiplication operation. Let, We have 3 numbers a, b, p To compute (a/b)p (a/b)p ≡ (a*(inverse(b)))p ≡ ((ap)*inverse(b)p)p NOTE: For the existence of inverse of 'b', 'b' and 'p' must be coprime For simplicity we take p as prime Time Complexity: O(log(b)) Example: ( 24 / 3 ) % 5 => 8 % 5 = 3 — (i) Now the inverse of 3 is 2 (24 * 2) % 5 = (24 % 5) * (2 % 5) = (4 * 2) % 5 = 3 — (ii) (i) and (ii) are equal hence the answer is correct.
Definition in file modular_division.cpp.
int main | ( | int | argc, |
char * | argv[] ) |
Main function.
argc | commandline argument count (ignored) |
argv | commandline array of arguments (ignored) |
Definition at line 113 of file modular_division.cpp.
uint64_t math::modular_division::mod_division | ( | uint64_t | a, |
uint64_t | b, | ||
uint64_t | p ) |
This function calculates modular division.
a | integer dividend |
b | integer divisor |
p | integer modulo |
Calculate the inverse of b
Calculate the final result
Definition at line 75 of file modular_division.cpp.
uint64_t math::modular_division::power | ( | uint64_t | a, |
uint64_t | b, | ||
uint64_t | c ) |
This function calculates a raised to exponent b under modulo c using modular exponentiation.
a | integer base |
b | unsigned integer exponent |
c | integer modulo |
Initialize the answer to be returned
Update a if it is more than or equal to c
In case a is divisible by c;
If b is odd, multiply a with answer
b must be even now
b = b/2
Definition at line 50 of file modular_division.cpp.
|
static |
Function for testing power function. test cases and assert statement.
void
Definition at line 89 of file modular_division.cpp.