modular exponentiation Algorithm

Modular exponentiation is an algorithm that efficiently computes the result of an exponentiation operation followed by a modular reduction. It is a fundamental operation in number theory, cryptography, and computer science, as it is used in many applications such as the RSA cryptosystem, primality testing, and the Diffie-Hellman key exchange protocol. The algorithm takes three inputs: a base number (a), an exponent (b), and a modulus (m). The goal of the algorithm is to compute the remainder of a raised to the power of b, divided by m (i.e., (a^b) % m) without having to calculate the full result of a^b, which can be computationally expensive for large values of a and b. The modular exponentiation algorithm relies on the properties of modular arithmetic and exponentiation to simplify the calculation. One of the most popular techniques to perform this operation is the "square and multiply" method, also known as "exponentiation by squaring." This method involves repeated squaring and multiplication of the base number (a) with itself, while keeping track of the intermediate results modulo m at each step. By breaking the exponent (b) into its binary representation, the algorithm can efficiently compute the final result by only using a logarithmic number of multiplications and modular reductions. This makes it a highly efficient and scalable algorithm, well-suited for applications that require working with large numbers and performing secure cryptographic operations.
// Modular exponentiation implemented in C++
// Given three numbers x, y and p, compute
// (power(x,y)) % p. where power(a,b) calculates a
// to power of b
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/math
// https://github.com/allalgorithms/cpp
//
// Contributed by: Rituparno Biswas
// Github: @roopbiswas
//
#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;

ll power(ll x, ll y, ll p)
{
	if(x==0)
		return 0;
	if(y==0)
		return 1;
	if (y%2==0)
	{
		ll g=power(x,y/2,p);
		return (g*g)%p;
	}
	else
	{
		ll g=power(x,y/2,p);
		return (x*(g*g)%p)%p;
	}
}

int main()
{
   ll x = 2,y = 5, p = 13;
   printf("Power is %lld", power(x, y, p));
   return 0;
}

LANGUAGE:

DARK MODE: