Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ square and multiply algorithm

#include <iostream>
#include <algorithm>

using std::cout;
using std::endl;
using std::string;
using std::stoi;

/**
 *
 * @param exponent
 * @return string => turns exponent into binary string
 */
string getBinary(int exponent) {

    string expo_Binary;

    while(exponent) {
        expo_Binary += (exponent%2) + '0';
        exponent /= 2;
    }
    reverse(expo_Binary.begin(),expo_Binary.end());

    return expo_Binary;
}

/**
 *
 * @param potenz
 * @param expo_Binary
 * @param modulo
 * @return int => remainder
 */
int getMod(int const base, string const& expo_Binary, int const modulo) {

    int remainder = base;

    for(int i = 1; i<expo_Binary.size(); i++) {
        remainder = (remainder * remainder) % modulo;
        remainder = ( (expo_Binary.at(i)-'0') == 1) ? (base * remainder) % modulo : remainder;
    }

    return remainder;
}

int main() {

    string expo_Binary = getBinary(373); // exponent
    int const remainder = getMod(23, expo_Binary, 747); //potenz, exponent, modulo
    cout << remainder << endl;   //print remainder

}
Comment

PREVIOUS NEXT
Code Example
Cpp :: cpprestsdk send file 
Cpp :: ifstream file (“code2.txt”); dev C++ 
Cpp :: bool nullable to bool c# 
Cpp :: lcm in c++ 
Cpp :: rc.local not running centos 6 
Cpp :: how atan work c++ 
Cpp :: c++ tuple push_back 
Cpp :: prefix using stack 
Cpp :: error: use of parameter outside function body before ] token c++ 
Cpp :: two dimensional array A[N,M] with the random numbers from 10 to 90. 
Cpp :: simple program for sign in and sign up in c++ 
Cpp :: input numbers to int c++ 
Cpp :: right rotation of array in c++ by one element 
Cpp :: what is c++ 
Cpp :: Access Elements in C++ Array 
Cpp :: cpp module 42 
Cpp :: check .h files syntax c++ 
Cpp :: reading matrix from text file in c++ and adding them and then storing them in oother c++ file 
Cpp :: private access specifier in c++ program 
Cpp :: https://stackoverflow.comInstance of a Character in a String c++ 
Cpp :: integrate sinx 
Cpp :: what does npl mean? 
Cpp :: map::begin 
Cpp :: punteros a arrays 
Cpp :: flutter container margin 
Cpp :: sfml get position 
Cpp :: find number of 1s in a binary cv::mat image 
Cpp :: Make them equal codechef solution in c++ 
Cpp :: how to take continuous input in c++ until any value. Like for example(taking input until giving q) 
Cpp :: stack in c++ data structure 
ADD CONTENT
Topic
Content
Source link
Name
4+5 =