Search
 
SCRIPT & CODE EXAMPLE
 

CPP

modular exponentiation algorithm c++

#include <iostream>
using namespace std;

int main()
{
    int b, n, m, x =1, a[10], i, k=0;
    int power;

    // input part
    cout<< "Enter base: ";
    cin>> b;

    cout<< "Enter power raised: ";
    cin>> n;

    cout<< "Enter modular value: ";
    cin>> m;

    power =  b % m;

    // converting value of n to binary
    for(i=0; n>0; i++)
    {
        a[i]=n%2;
        n= n/2;
        k++;
    }

    // getting value of x
    for(i=0; i<k; i++)
    {
        if (a[i] == 1)
        {
            x = (x * power) % m;
            power = (power * power) % m;
        }

        else
            power = (power * power) % m;
    }

    // x is the result of modular expansion (b^n mod m)
    cout<< x;

    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: declare empty array in c++ 
Cpp :: c++ split string 
Cpp :: c++ insert hashmap 
Cpp :: if else in c++ 
Cpp :: assignment operator with pointers c++ 
Cpp :: initialize a vector with same values 
Cpp :: DS1302 
Cpp :: How to pass a multidimensional array to a function in C and C++ 
Cpp :: string append at position c++ 
Cpp :: cpp undefined reference to function 
Cpp :: what algorithm does bitcoin use 
Cpp :: concatenate string in cpp 
Cpp :: std::string substr 
Cpp :: valid parentheses in c++ 
Cpp :: C++ pointer to base class 
Cpp :: c++ main function parameters 
Cpp :: max and min function in c++ 
Cpp :: c++ visual studio 
Cpp :: Initialize Vector Iterator with end() function 
Cpp :: c++ void poiinter 
Cpp :: crud with template c++ 
Cpp :: c++ friend keyword 
Cpp :: c++ get microseconds since epoch 
Cpp :: nmake.exe is not found in the windows 
Cpp :: how to print double value up to 9 decimal places in c++ 
Cpp :: int and char in c++ compiler 
Cpp :: how to change the icon of an exe in c++ 
Cpp :: nothrow new in cpp 
Cpp :: variadic template constructor matches better than copy constructor 
Cpp :: how to add values in empty array using python 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =