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 : 4Input : 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 x^y
is being calculated it can get very large so instead we have to calculate (x^y
%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)
- 2^k
-ary method.
Binary Exponentiation
As described in this article we will be using following formula to recursively calculate (x^y
%modulus value): {\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}}}
C++
// C++ program to compute exponential
// value under modulo using binary
// exponentiation.
#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 exponent is even value
if (exp % 2 == 0)
return t;
// if exponent is odd value
else
return ((base % N) * t) % N;
}
// Driver Code
int main()
{
long int base = 5;
long int exp = 100000;
long int modulo = exponentiation(base, exp);
cout << modulo << endl;
return 0;
}
// This Code is contributed by mits
Java
// Java program to compute exponential value under modulo
// using binary exponentiation.
import java.util.*;
import java.lang.*;
import java.io.*;
class exp_sq {
static long N = 1000000007L; // prime modulo value
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 exponent is even value
if (exp % 2 == 0)
return t;
// if exponent is odd value
else
return ((base % N) * t) % N;
}
}
Python3
# Python3 program to compute
# exponential value under
# modulo using binary
# exponentiation.
# prime modulo value
N = 1000000007;
# Function code
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 exponent is
# even value
if (exp % 2 == 0):
return t;
# if exponent is
# odd value
else:
return ((bas % N) * t) % N;
# Driver code
bas = 5;
exp = 100000;
modulo = exponentiation(bas, exp);
print(modulo);
# This code is contributed
# by mits
C#
// C# program to compute exponential
// value under modulo using binary
// exponentiation.
using System;
class GFG {
// prime modulo value
static long N = 1000000007L;
// Driver code
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 exponent is even value
if (exp % 2 == 0)
return t;
// if exponent is odd value
else
return ((bas % N) * t) % N;
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// JavaScript program to compute
// exponential value under
// modulo using binary
// exponentiation.
// prime modulo value
let N = 1000000007;
// Function code
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 exponent is
// even value
if (exp % 2 == 0){
return t;
}
// if exponent is
// odd value
else{
return ((base % N) * t) % N;
}
}
// Driver code
let base = 5;
let exp = 100000;
let modulo = exponentiation(base, exp);
document.write(modulo);
document.write(base);
// This code is contributed by Gautam goel (gautamgoel962)
</script>
PHP
<?php
// PHP program to compute exponential
// value under modulo using binary
// exponentiation.
// prime modulo value
$N = 1000000007;
// Function code
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 exponent is
// even value
if ($exp % 2 == 0)
return $t;
// if exponent is
// odd value
else
return (($bas % $N) *
$t) % $N;
}
// Driver code
$bas = 5;
$exp = 100000;
$modulo = exponentiation($bas, $exp);
echo ($modulo);
// This code is contributed by ajit
?>
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)
-ary method:
In this algorithm we will be expanding the exponent in base 2^k
(k>=1), which is somehow similar to above method except we are not using recursion this method uses comparatively less memory and time.
C++
// C++ program to compute exponential value using (2^k)
// -ary method.
#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)
{
// for cases where exponent
// is not an even value
if (exp % 2 != 0)
t = (t * base) % N;
base = (base * base) % N;
exp /= 2;
}
return t % N;
}
// Driver code
int main()
{
long base = 5;
long exp = 100000;
long modulo = exponentiation(base, exp);
cout << (modulo);
return 0;
}
// This code is contributed by Rajput-Ji
Java
// Java program to compute exponential value using (2^k)
// -ary method.
import java.util.*;
import java.lang.*;
import java.io.*;
class exp_sq {
static long N = 1000000007L; // prime modulo value
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) {
// for cases where exponent
// is not an even value
if (exp % 2 != 0)
t = (t * base) % N;
base = (base * base) % N;
exp /= 2;
}
return t % N;
}
}
Python3
# Python3 program to compute
# exponential value
# using (2^k) -ary method.
# prime modulo value
N = 1000000007;
def exponentiation(bas, exp):
t = 1;
while(exp > 0):
# for cases where exponent
# is not an even value
if (exp % 2 != 0):
t = (t * bas) % N;
bas = (bas * bas) % N;
exp = int(exp / 2);
return t % N;
# Driver Code
bas = 5;
exp = 100000;
modulo = exponentiation(bas,exp);
print(modulo);
# This code is contributed
# by mits
C#
// C# program to compute
// exponential value
// using (2^k) -ary method.
using System;
class GFG
{
// prime modulo value
static long N = 1000000007L;
static long exponentiation(long bas,
long exp)
{
long t = 1L;
while (exp > 0)
{
// for cases where exponent
// is not an even value
if (exp % 2 != 0)
t = (t * bas) % N;
bas = (bas * bas) % N;
exp /= 2;
}
return t % N;
}
// Driver Code
public static void Main ()
{
long bas = 5;
long exp = 100000;
long modulo = exponentiation(bas,
exp);
Console.WriteLine(modulo);
}
}
//This code is contributed by ajit
JavaScript
// JavaScript program to compute
// exponential value
// using (2^k) -ary method.
// prime modulo value
let N = 1000000007n;
function exponentiation(bas, exp)
{
let t = 1n;
while(exp > 0n)
{
// for cases where exponent
// is not an even value
if (exp % 2n != 0n)
t = (t * bas) % N;
bas = (bas * bas) % N;
exp >>= 1n;
}
return t % N;
}
// Driver Code
let bas = 5n;
let exp = 100000n;
let modulo = exponentiation(bas,exp);
console.log(Number(modulo));
// This code is contributed
// by phasing17
PHP
<?php
// PHP program to compute
// exponential value
// using (2^k) -ary method.
// prime modulo value
$N = 1000000007;
function exponentiation($bas,
$exp)
{
global $N;
$t = 1;
while ($exp > 0)
{
// for cases where exponent
// is not an even value
if ($exp % 2 != 0)
$t = ($t * $bas) % $N;
$bas = ($bas * $bas) % $N;
$exp = (int)$exp / 2;
}
return $t % $N;
}
// Driver Code
$bas = 5;
$exp = 100000;
$modulo = exponentiation($bas,
$exp);
echo ($modulo);
// This code is contributed
// by ajit
?>
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; // prime modulo value
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
// Java program to compute exponential value under modulo
// using Bit Manipulation.
import java.util.*;
import java.lang.*;
import java.io.*;
class exp_sq {
static long mod = 1000000007L; // prime modulo value
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
# Function to square the multiply
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
# Driver Code
base = 5
exp = 100000
modulo = square_multiply(base, exp)
print(modulo)
C#
using System;
public class Program {
const long mod = 1000000007L; // prime modulo value
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; // prime modulo value (BigInt)
function squareMultiply(base, exp) {
let b = 1n; // Initialize b as BigInt
let A = base % mod;
if (exp & 1n) { // Check if exp is odd (using BigInt)
b = base % mod;
}
exp >>= 1n; // Right shift exp by 1 (using BigInt)
while (exp > 0n) {
A = (A * A) % mod;
if (exp & 1n) {
b = (A * b) % mod;
}
exp >>= 1n;
}
return b % mod;
}
const base = 5n; // Initialize base as BigInt
const exp = 100000n; // Initialize exp as BigInt
const modulo = squareMultiply(base, exp);
console.log(modulo.toString()); // Output the result
Time Complexity -- O( log(exp) )
Space Complexity -- O(1)
Applications: Besides fast calculation of x^y
this method have several other advantages, like it is used in cryptography, in calculating Matrix Exponentiation et cetera.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem