TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
modular_inverse_simple.cpp File Reference

Simple implementation of modular multiplicative inverse More...

#include <cassert>
#include <cstdint>
#include <iostream>
Include dependency graph for modular_inverse_simple.cpp:

Go to the source code of this file.

Functions

uint64_t imod (uint64_t x, uint64_t y)
 for assert
 
static void test ()
 self-test implementations
 
int main ()
 Main function.
 

Detailed Description

Simple implementation of modular multiplicative inverse

this algorithm calculates the modular inverse x^{-1} \mod y iteratively

Definition in file modular_inverse_simple.cpp.

Function Documentation

◆ imod()

uint64_t imod ( uint64_t x,
uint64_t y )

for assert

for IO operations

Function imod Calculates the modular inverse of x with respect to y, x^{-1} \mod y

Parameters
xnumber
ynumber
Returns
the modular inverse

Definition at line 21 of file modular_inverse_simple.cpp.

21 {
22 uint64_t aux = 0; // auxiliary variable
23 uint64_t itr = 0; // iteration counter
24
25 do { // run the algorithm while not find the inverse
26 aux = y * itr + 1;
27 itr++;
28 } while (aux % x); // while module aux % x non-zero
29
30 return aux / x;
31}

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 59 of file modular_inverse_simple.cpp.

59 {
60 test(); // run self-test implementations
61};
static void test()
self-test implementations

◆ test()

static void test ( )
static

self-test implementations

Returns
void

Definition at line 37 of file modular_inverse_simple.cpp.

37 {
38 std::cout << "First case testing... \n";
39 // for a = 3 and b = 11 return 4
40 assert(imod(3, 11) == 4);
41 std::cout << "\nPassed!\n";
42
43 std::cout << "Second case testing... \n";
44 // for a = 3 and b = 26 return 9
45 assert(imod(3, 26) == 9);
46 std::cout << "\nPassed!\n";
47
48 std::cout << "Third case testing... \n";
49 // for a = 7 and b = 26 return 15
50 assert(imod(7, 26) == 15);
51 std::cout << "\nPassed!\n";
52
53 std::cout << "\nAll test cases have successfully passed!\n";
54}
uint64_t imod(uint64_t x, uint64_t y)
for assert