Exponential Squaring (Fast Modulo Multiplication)
Last Updated :
03 Oct, 2023
Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7
Examples:
Input : base = 2, exp = 2
Output : 4
Input : base = 5, exp = 100000
Output : 754573817
In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the values of [Tex]x^y
[/Tex]is being calculated it can get very large so instead we have to calculate ([Tex]x^y
[/Tex]%modulus value.) We can use the modulus in our naive way by using modulus on all the intermediate steps and take modulus at the end, but in competitions it will definitely show TLE. So, what we can do. The answer is we can try exponentiation by squaring which is a fast method for calculating exponentiation of a number. Here we will be discussing two most common/important methods:
- Basic Method(Binary Exponentiation)
- [Tex]2^k
[/Tex]-ary method.
Binary Exponentiation
As described in this article we will be using following formula to recursively calculate ([Tex]x^y
[/Tex]%modulus value): [Tex]{\displaystyle x^{n}={\begin{cases}x\,(x^{2})^{\frac {n-1}{2}},&{\mbox{if }}n{\mbox{ is odd}}\\(x^{2})^{\frac {n}{2}},&{\mbox{if }}n{\mbox{ is even}}.\end{cases}}}
[/Tex]
C++
#include<iostream>
using namespace std;
#define N 1000000007 // prime modulo value
long int exponentiation(long int base,
long int exp)
{
if (exp == 0)
return 1;
if (exp == 1)
return base % N;
long int t = exponentiation(base, exp / 2);
t = (t * t) % N;
if (exp % 2 == 0)
return t;
else
return ((base % N) * t) % N;
}
int main()
{
long int base = 5;
long int exp = 100000;
long int modulo = exponentiation(base, exp);
cout << modulo << endl;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class exp_sq {
static long N = 1000000007L;
public static void main(String[] args)
{
long base = 5;
long exp = 100000;
long modulo = exponentiation(base, exp);
System.out.println(modulo);
}
static long exponentiation(long base, long exp)
{
if (exp == 0)
return 1;
if (exp == 1)
return base % N;
long t = exponentiation(base, exp / 2);
t = (t * t) % N;
if (exp % 2 == 0)
return t;
else
return ((base % N) * t) % N;
}
}
|
Python3
N = 1000000007;
def exponentiation(bas, exp):
if (exp == 0):
return 1;
if (exp == 1):
return bas % N;
t = exponentiation(bas, int(exp / 2));
t = (t * t) % N;
if (exp % 2 == 0):
return t;
else:
return ((bas % N) * t) % N;
bas = 5;
exp = 100000;
modulo = exponentiation(bas, exp);
print(modulo);
|
C#
using System;
class GFG {
static long N = 1000000007L;
public static void Main()
{
long bas = 5;
long exp = 100000;
long modulo = exponentiation(bas, exp);
Console.Write(modulo);
}
static long exponentiation(long bas, long exp)
{
if (exp == 0)
return 1;
if (exp == 1)
return bas % N;
long t = exponentiation(bas, exp / 2);
t = (t * t) % N;
if (exp % 2 == 0)
return t;
else
return ((bas % N) * t) % N;
}
}
|
Javascript
<script>
let N = 1000000007;
function exponentiation(base, exp){
if (exp == 0){
return 1;
}
if (exp == 1){
return (base % N);
}
let t = exponentiation(base,exp/2);
t = ((t * t) % N);
console.log(t);
if (exp % 2 == 0){
return t;
}
else{
return ((base % N) * t) % N;
}
}
let base = 5;
let exp = 100000;
let modulo = exponentiation(base, exp);
document.write(modulo);
document.write(base);
</script>
|
PHP
<?php
$N = 1000000007;
function exponentiation($bas, $exp)
{
global $N ;
if ($exp == 0)
return 1;
if ($exp == 1)
return $bas % $N;
$t = exponentiation($bas,
$exp / 2);
$t = ($t * $t) % $N;
if ($exp % 2 == 0)
return $t;
else
return (($bas % $N) *
$t) % $N;
}
$bas = 5;
$exp = 100000;
$modulo = exponentiation($bas, $exp);
echo ($modulo);
?>
|
Output :
754573817
Time Complexity: O(log exp) since the binary exponentiation algorithm divides the exponent by 2 at each recursive call, resulting in a logarithmic number of recursive calls.
Space Complexity: O(log exp)
[Tex]
[/Tex]-ary method:
In this algorithm we will be expanding the exponent in base [Tex]2^k
[/Tex](k>=1), which is somehow similar to above method except we are not using recursion this method uses comparatively less memory and time.
C++
#include<bits/stdc++.h>
using namespace std;
#define N 1000000007L; // prime modulo value
long exponentiation(long base, long exp)
{
long t = 1L;
while (exp > 0)
{
if (exp % 2 != 0)
t = (t * base) % N;
base = (base * base) % N;
exp /= 2;
}
return t % N;
}
int main()
{
long base = 5;
long exp = 100000;
long modulo = exponentiation(base, exp);
cout << (modulo);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class exp_sq {
static long N = 1000000007L;
public static void main(String[] args)
{
long base = 5;
long exp = 100000;
long modulo = exponentiation(base, exp);
System.out.println(modulo);
}
static long exponentiation(long base, long exp)
{
long t = 1L;
while (exp > 0) {
if (exp % 2 != 0)
t = (t * base) % N;
base = (base * base) % N;
exp /= 2;
}
return t % N;
}
}
|
Python3
N = 1000000007;
def exponentiation(bas, exp):
t = 1;
while(exp > 0):
if (exp % 2 != 0):
t = (t * bas) % N;
bas = (bas * bas) % N;
exp = int(exp / 2);
return t % N;
bas = 5;
exp = 100000;
modulo = exponentiation(bas,exp);
print(modulo);
|
C#
using System;
class GFG
{
static long N = 1000000007L;
static long exponentiation(long bas,
long exp)
{
long t = 1L;
while (exp > 0)
{
if (exp % 2 != 0)
t = (t * bas) % N;
bas = (bas * bas) % N;
exp /= 2;
}
return t % N;
}
public static void Main ()
{
long bas = 5;
long exp = 100000;
long modulo = exponentiation(bas,
exp);
Console.WriteLine(modulo);
}
}
|
Javascript
let N = 1000000007n;
function exponentiation(bas, exp)
{
let t = 1n;
while(exp > 0n)
{
if (exp % 2n != 0n)
t = (t * bas) % N;
bas = (bas * bas) % N;
exp >>= 1n;
}
return t % N;
}
let bas = 5n;
let exp = 100000n;
let modulo = exponentiation(bas,exp);
console.log(Number(modulo));
|
PHP
<?php
$N = 1000000007;
function exponentiation($bas,
$exp)
{
global $N;
$t = 1;
while ($exp > 0)
{
if ($exp % 2 != 0)
$t = ($t * $bas) % $N;
$bas = ($bas * $bas) % $N;
$exp = (int)$exp / 2;
}
return $t % $N;
}
$bas = 5;
$exp = 100000;
$modulo = exponentiation($bas,
$exp);
echo ($modulo);
?>
|
Output :
754573817
Time Complexity: O(log exp)
Space Complexity: O(1)
Bit-Manipulation Method
The basic idea behind the algorithm is to use the binary representation of the exponent to compute the power in a faster way.
Specifically, if we can represent the exponent as a sum of powers of 2, then we can use the fact that x^(a+b) = x^a * x^b to compute the power.
Approach :
The steps of the algorithm are as follows :
1. Initialize a result variable to 1, and a base variable to the given base value.
2. Convert the exponent to binary format.
3. Iterate over the bits of the binary representation of the exponent, from right to left.
4. For each bit, square the current value of the base.
5. If the current bit is 1, multiply the result variable by the current value of the base.
6. Divide the exponent by 2, discarding the remainder.
7. Continue the iteration until all bits of the exponent have been processed.
8. Return the result variable modulo the given modulus value.
C++
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007LL;
long long squareMultiply(long long base, long long exp) {
long long b = 1LL;
long long A = base % mod;
if (exp & 1LL) {
b = base % mod;
}
exp >>= 1LL;
while (exp > 0) {
A = (A * A) % mod;
if (exp & 1LL) {
b = (A * b) % mod;
}
exp >>= 1LL;
}
return b % mod;
}
int main() {
long long base = 5LL;
long long exp = 100000LL;
long long modulo = squareMultiply(base, exp);
cout << modulo << endl;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class exp_sq {
static long mod = 1000000007L;
public static void main(String[] args)
{
long base = 5;
long exp = 100000;
long modulo = squareMultiply(base, exp);
System.out.println(modulo);
}
static long squareMultiply(long base, long exp)
{
long b = 1;
long A = base;
if((exp & 1) == 1){
b = base % mod;
}
exp = (exp >> 1);
while(exp > 0){
A = (A * A) % mod;
if((exp & 1) == 1){
b = (A * b) % mod;
}
exp = (exp >> 1);
}
return b % mod;
}
}
|
Python3
mod = 1000000007
def square_multiply(base, exp):
b = 1
A = base % mod
if exp & 1:
b = base % mod
exp >>= 1
while exp > 0:
A = (A * A) % mod
if exp & 1:
b = (A * b) % mod
exp >>= 1
return b % mod
base = 5
exp = 100000
modulo = square_multiply(base, exp)
print(modulo)
|
C#
using System;
public class Program {
const long mod = 1000000007L;
static long squareMultiply(long baseNum, long exponent)
{
long b = 1L;
long A = baseNum % mod;
if ((exponent & 1L) == 1L) {
b = baseNum % mod;
}
exponent >>= 1;
while (exponent > 0) {
A = (A * A) % mod;
if ((exponent & 1L) == 1L) {
b = (A * b) % mod;
}
exponent >>= 1;
}
return b % mod;
}
static public void Main()
{
long baseNum = 5L;
long exponent = 100000L;
long modulo = squareMultiply(baseNum, exponent);
Console.WriteLine(modulo);
}
}
|
Javascript
const mod = 1000000007n;
function squareMultiply(base, exp) {
let b = 1n;
let A = base % mod;
if (exp & 1n) {
b = base % mod;
}
exp >>= 1n;
while (exp > 0n) {
A = (A * A) % mod;
if (exp & 1n) {
b = (A * b) % mod;
}
exp >>= 1n;
}
return b % mod;
}
const base = 5n;
const exp = 100000n;
const modulo = squareMultiply(base, exp);
console.log(modulo.toString());
|
Time Complexity — O( log(exp) )
Space Complexity — O(1)
Applications: Besides fast calculation of [Tex]x^y
[/Tex]this method have several other advantages, like it is used in cryptography, in calculating Matrix Exponentiation et cetera.
Similar Reads
Modular Arithmetic
Modular arithmetic is the branch of arithmetic mathematics related to the "mod" functionality. Basically, modular arithmetic is related to the computation of a "mod" of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other.
12 min read
Modular Exponentiation (Power in Modular Arithmetic)
Modular Exponentiation is the process of computing: xy (modââp). where x, y, and p are integers. It efficiently calculates the remainder when xy is divided by p or (xy) % p, even for very large y. Examples : Input: x = 2, y = 3, p = 5Output: 3Explanation: 2^3 % 5 = 8 % 5 = 3.Input: x = 2, y = 5, p =
8 min read
Modular multiplicative inverse
Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that: A * X â¡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*
15+ min read
Multiplicative order
In number theory, given an integer A and a positive integer N with gcd( A , N) = 1, the multiplicative order of a modulo N is the smallest positive integer k with A^k( mod N ) = 1. ( 0 < K < N ) Examples : Input : A = 4 , N = 7 Output : 3 explanation : GCD(4, 7) = 1 A^k( mod N ) = 1 ( smallest
7 min read
Modular Multiplication
Modular arithmetic, or clock arithmetic, is a system of arithmetic for integers, where numbers "wrap around" upon reaching a certain valueâthe modulus. This mathematical concept is widely used in various fields such as computer science, cryptography, number theory, and even everyday situations like
6 min read
Modular Division
Modular division is the process of dividing one number by another in modular arithmetic. In modular arithmetic, division is defined differently from regular arithmetic because there is no direct "division" operation. Instead, modular division involves multiplying by the modular multiplicative invers
10 min read
Modulus on Negative Numbers
The modulus operator, denoted as %, returns the remainder when one number (the dividend) is divided by another number (the divisor). Modulus of Positive NumbersProblem: What is 7 mod 5?Solution: From Quotient Remainder Theorem, Dividend=Divisor*Quotient + Remainder7 = 5*1 + 2, which gives 2 as the r
7 min read
Problems on Modular Arithmetic
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
11 min read
Find sum of modulo K of first N natural number
Given two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
9 min read
How to compute mod of a big number?
Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer. Examples : Input: num = "12316767678678", a = 10 Output: num (mod a) ? 8 The idea is to process all digits one by one and use the property that xy (mod a) ? ((x
4 min read
Exponential Squaring (Fast Modulo Multiplication)
Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7 Examples: Input : base = 2, exp = 2Output : 4Input : base = 5, exp = 100000Output : 754573817In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the valu
12 min read
Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
Given integers x1, x2, x3......xn, b, and m, we are supposed to find the result of ((x1*x2....xn)/b)mod(m). Example 1: Suppose that we are required to find (55C5)%(1000000007) i.e ((55*54*53*52*51)/120)%1000000007 Naive Method : Simply calculate the product (55*54*53*52*51)= say x,Divide x by 120 an
9 min read
Modular Multiplication
Modular arithmetic, or clock arithmetic, is a system of arithmetic for integers, where numbers "wrap around" upon reaching a certain valueâthe modulus. This mathematical concept is widely used in various fields such as computer science, cryptography, number theory, and even everyday situations like
6 min read
Difference between Modulo and Modulus
In the world of Programming and Mathematics we often encounter the two terms "Modulo" and "Modulus". In programming we use the operator "%" to perform modulo of two numbers. It basically finds the remainder when a number x is divided by another number N. It is denoted by : x mod N where x : Dividend
2 min read
Modulo Operations in Programming With Negative Results
In programming, the modulo operation gives the remainder or signed remainder of a division, after one integer is divided by another integer. It is one of the most used operators in programming. This article discusses when and why the modulo operation yields a negative result. Examples: In C, 3 % 2 r
15+ min read
Modulo 10^9+7 (1000000007)
In most programming competitions, we are required to answer the result in 10^9+7 modulo. The reason behind this is, if problem constraints are large integers, only efficient algorithms can solve them in an allowed limited time.What is modulo operation: The remainder obtained after the division opera
10 min read
Fibonacci modulo p
The Fibonacci sequence is defined as [Tex]F_i [/Tex]= [Tex]F_{i-1} [/Tex]+ [Tex]F_{i-2} [/Tex]where [Tex]F_1 [/Tex]= 1 and [Tex]F_2 [/Tex]= 1 are the seeds. For a given prime number p, consider a new sequence which is (Fibonacci sequence) mod p. For example for p = 5, the new sequence would be 1, 1,
5 min read
Modulo of a large Binary String
Given a large binary string str and an integer K, the task is to find the value of str % K.Examples: Input: str = "1101", K = 45 Output: 13 decimal(1101) % 45 = 13 % 45 = 13 Input: str = "11010101", K = 112 Output: 101 decimal(11010101) % 112 = 213 % 112 = 101 Approach: It is known that (str % K) wh
5 min read
Modular multiplicative inverse from 1 to n
Give a positive integer n, find modular multiplicative inverse of all integer from 1 to n with respect to a big prime number, say, 'prime'. The modular multiplicative inverse of a is an integer 'x' such that. a x ? 1 (mod prime) Examples: Input : n = 10, prime = 17 Output : 1 9 6 13 7 3 5 15 2 12 Ex
9 min read
Modular exponentiation (Recursive)
Given three numbers a, b and c, we need to find (ab) % cNow why do â% câ after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store suc
6 min read
Chinese Remainder Theorem
Introduction to Chinese Remainder Theorem
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that:Â x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Basically, we are given k numbers whic
8 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[
11 min read
Cyclic Redundancy Check and Modulo-2 Division
CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key
15+ min read
Using Chinese Remainder Theorem to Combine Modular equations
Given N modular equations: A ? x1mod(m1) . . A ? xnmod(mn) Find x in the equation A ? xmod(m1*m2*m3..*mn) where mi is prime, or a power of a prime, and i takes values from 1 to n. The input is given as two arrays, the first being an array containing values of each xi, and the second array containing
12 min read