Open In App
Related Articles

Binary Exponentiation for Competitive Programming

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In competitive programming, we often need to do a lot of big number calculations fast. Binary exponentiation is like a super shortcut for doing powers and can make programs faster. This article will show you how to use this powerful trick to enhance your coding skills.

What is Binary Exponentiation?

Binary Exponentiation or Exponentiation by squaring is the process of calculating a number raised to the power another number (AB) in Logarithmic time of the exponent or power, which speeds up the execution time of the program.

Why to Use Binary Exponentiation?

Whenever we need to calculate (AB), we can simple calculate the result by taking the result as 1 and multiplying A for exactly B times. The time complexity for this approach is O(B) and will fail when values of B in order of 108 or greater. This is when we can use Binary exponentiation because it can calculate the result in O(log(B)) time complexity, so we can easily calculate the results for larger values of B in order of 1018 or less.

Idea Behind Binary Exponentiation:

When we are calculating (AB), we can have 3 possible positive values of B:

  • Case 1: If B = 0, whatever be the value of A, our result will be 1.
  • Case 2: If B is an even number, then instead of calculating (AB), we can calculate ((A2)B/2) and the result will be same.
  • Case 3: If B is an odd number, then instead of calculating (AB), we can calculate (A * (A(B – 1)/2)2),

Examples:

2 12 = (2) 2 * 6
= (4) 6
= (4) 2 * 3
= (16) 3
= 16 * (16) 2
= 16 * (256) 1

Recursive Implementation of Binary Exponentiation:

C++

#include <bits/stdc++.h>
using namespace std;
 
long long power(long long A, long long B)
{
    if (B == 0)
        return 1;
 
    long long res = power(A, B / 2);
 
    if (B % 2)
        return res * res * A;
    else
        return res * res;
}
 
int main()
{
    cout << power(2, 12) << "\n";
    return 0;
}

                    

Java

import java.io.*;
class GFG {
    static long power(long A, long B) {
        if (B == 0)
            return 1;
 
        long res = power(A, B / 2);
 
        if (B % 2 == 1)
            return res * res * A;
        else
            return res * res;
    }
 
    public static void main(String[] args) {
        System.out.println(power(2, 12));
    }
}
//This code is contributed by Rohit Singh

                    

Python3

def power(A, B):
    if B == 0:
        return 1
 
    res = power(A, B // 2)
 
    if B % 2:
        return res * res * A
    else:
        return res * res
 
if __name__ == "__main__":
    print(power(2, 12))

                    

C#

using System;
 
class Program
{
    // Recursive function to calculate the power of a number (A^B)
    static long Power(long A, long B)
    {
        // Base case: A^0 is always 1
        if (B == 0)
            return 1;
 
        // Recursive calculation of A^(B/2)
        long res = Power(A, B / 2);
 
        // Multiply the result by itself
        res *= res;
 
        // If B is odd, multiply by A one more time
        if (B % 2 != 0)
            res *= A;
 
        return res;
    }
 
    static void Main()
    {
        // Example: Calculate and print the result of 2^12
        Console.WriteLine(Power(2, 12));
    }
}

                    

Javascript

// Function to calculate the power of a number A raised to the power of B
function power(A, B) {
    if (B === 0) {
        return 1;
    }
 
    let res = power(A, Math.floor(B / 2));
 
    if (B % 2 === 1) {
        return res * res * A;
    } else {
        return res * res;
    }
}
 
// Driver code
console.log(power(2, 12));

                    

Output
4096

Iterative Implementation of Binary Exponentiation:

C++

#include <bits/stdc++.h>
using namespace std;
 
long long power(long long a, long long b) {
    long long result = 1;
    while(b) {
        if (b & 1)
        result = result * a;
        a = a * a;
        b >>= 1;
    }
    return result;
}
 
int main() {
    cout<<power(2, 12)<<"\n";
    return 0;
}

                    

Java

public class Main {
    public static long power(long a, long b) {
        long result = 1;
        while (b > 0) {
            if ((b & 1) == 1) {
                result *= a;
            }
            a *= a;
            b >>= 1;
        }
        return result;
    }
 
    public static void main(String[] args) {
        System.out.println(power(2, 12));
    }
}

                    

Python3

def power(a, b):
    result = 1
    while b:
        if b & 1:
            result = result * a
        a = a * a
        b >>= 1
    return result
 
if __name__ == "__main__":
    print(power(2, 12))

                    

C#

using System;
 
class Program {
    // Function to calculate power
    static long Power(long a, long b)
    {
        long result = 1;
        while (b > 0) {
            if ((b & 1) == 1)
                result *= a;
            a *= a;
            b >>= 1;
        }
        return result;
    }
 
    static void Main() { Console.WriteLine(Power(2, 12)); }
}

                    

Javascript

// Function to calculate the power of a number
function power(a, b) {
    let result = 1;
    while (b > 0) {
        // If b is odd, multiply result by a
        if (b & 1) {
            result *= a;
        }
        // Square a
        a *= a;
        // Divide b by 2 using bitwise right shift
        b >>= 1;
    }
    return result;
}
 
// Main function
function main() {
    // Output the result of power(2, 12)
    console.log(power(2, 12));
}
 
// Call the main function
main();

                    

Output
4096




Even though, both the iterative and recursive approach have the same time complexity, the iterative approach is still faster because there are no overheads for recursive calls.

Use Cases of Binary Exponentiation in Competitive Programming:

1. Fast Computation of Nth Fibonacci Number:

We can compute Nth Fibonacci Number by simply running a loop till N and in every iteration i, we calculate the ith Fibonacci number using (i-1)th and (i-2)th iteration. But this approach runs in linear time complexity, that is O(N). But, if we are concerned with simply the Nth Fibonacci number and not every number before it, then we can compute it in O(logN) by using matrix exponentiation, where we build a 2тип2 matrix to transition from (i-2)th and (i-1)th Fibonacci number to (i-1)th and ith Fibonacci number.

Click here to expand your knowledge about Matrix Exponentiation

2. Compute a large number modulo M:

It is hardly to see any problem which is all about to compute AB, but Binary Exponentiation comes in handy when our answer becomes too large to be stored as an integer, that is greater than INT_MAX. There are many problems which asks us to count the number of ways to do something and as the number of ways are too large to be stored in an Integer variable, the question asks us to print the answer modulo 1000000007 or modulo 998244353. Since, it is proved here, that

(A * B) mod M = ((A mod M) * (B mod M)) mod M

Therefore, Binary Exponentiation is very useful in computing AB mod M.

C++

#include <bits/stdc++.h>;
using namespace std;
 
const int mod = 1e9 + 7;
 
long long power(long long a, long long b)
{
    long long result = 1;
    while (b) {
        if (b & 1)
            result = (result * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return result;
}
 
int main()
{
    cout << power(2, 42) << "\n";
    return 0;
}

                    

Java

import java.util.*;
 
public class Main {
    // Constant representing the modulo value
    static final int mod = 1000000007;
 
    // Function to calculate the power of a number (a) raised to the power of b modulo mod
    public static long power(long a, long b) {
        long result = 1;
        while (b > 0) {
            // If the current bit of b is set, multiply the result by a
            if ((b & 1) == 1)
                result = (result * a) % mod;
             
            // Square the value of a and reduce it modulo mod
            a = (a * a) % mod;
             
            // Right shift b to move to the next bit
            b >>= 1;
        }
        return result;
    }
 
    public static void main(String[] args) {
        // Output the result of 2^42 modulo mod
        System.out.println(power(2, 42));
    }
}

                    

Python3

# Python Implementation
mod = 10**9 + 7
 
def power(a, b):
    result = 1
    while b:
        if b & 1:
            result = (result * a) % mod
        a = (a * a) % mod
        b >>= 1
    return result
 
print(power(2, 42))
 
# This code is contributed by Sakshi

                    

Output
46480318




3. Apply Permutation of a given Sequence large number of times:

Let’s suppose, we are given a Permutation P and a Sequence S and we need to apply P to S for a large number of times (say K), then we can easily compute the final sequence by using Binary Exponentiation.

Examples:

P = [2, 3, 4, 1], S = [2, 1, 3, 4]
After applying permutation P to Sequence S once,
S’ = [1, 3, 4, 2]
Explanation:
S'[1] = S[P[1]] = S[2] = 1
S'[2] = S[P[2]] = S[3] = 3
S'[3] = S[P[3]] = S[4] = 4
S'[4] = S[P[4]] = S[1] = 2

After applying permutation P to Sequence S twice,
S” = [3, 4, 2, 1]
Explanation:
S”[1] = S'[P[1]] = S'[2] = S[P[2]] = S[3] = 3
S”[2] = S'[P[2]] = S'[3] = S[P[3]] = S[4] = 4
S”[3] = S'[P[3]] = S'[4] = S[P[4]] = S[1] = 2
S”[4] = S'[P[4]] = S'[1] = S[P[1]] = S[2] = 1

Observations: If we observe carefully, in the above example instead of applying permutation P to S twice, if we apply permutation P in itself (P’) and then apply it on S once, we will get the same result.

P = [2, 3, 4, 1], S = [2, 1, 3, 4]
After applying permutation P to itself once,
P’ = [3, 4, 1, 2]
Explanation:
P'[1] = P[P[1]] = P[2] = 3
P'[2] = P[P[2]] = P[3] = 4
P'[3] = P[P[3]] = P[4] = 1
P'[4] = P[P[4]] = P[1] = 2

Now, applying permutation P’ to S,
S”[1] = S[P'[1]] = S[3] = 3
S”[2] = S[P'[2]] = S[4] = 4
S”[3] = S[P'[3]] = S[1] = 2
S”[4] = S[P'[4]] = S[2] = 1

Therefore, it is clear that applying a permutation P to a sequence S for N times is equal to applying permutation P’ to sequence S for N/2 times and we can simply solve this using Binary Exponentiation:

C++

#include <bits/stdc++.h>
using namespace std;
 
// binary exponentiation
void apply(vector<int>& S, vector<int>& P)
{
    vector<int> temp(S.size());
    for (int i = 1; i < S.size(); i++) {
        temp[i] = S[P[i]];
    }
    for (int i = 1; i < S.size(); i++)
        S[i] = temp[i];
}
 
// Function to apply Permutation P to Sequence S
// K number of times
void solve(vector<int>& S, vector<int>& P, int K)
{
    while (K) {
        if (K & 1)
            apply(S, P);
        apply(P, P);
        K >>= 1;
    }
}
int main()
{
    vector<int> P{ 0, 2, 3, 4, 1 };
    vector<int> S{ 0, 2, 1, 3, 4 };
    int K = 2;
    solve(S, P, K);
    cout << "New Sequence = ";
    for (int i = 1; i < S.size(); i++)
        cout << S[i] << " ";
    return 0;
}

                    

Python3

# Binary exponentiation
def apply(S, P):
    temp = [0] * len(S)
    for i in range(1, len(S)):
        temp[i] = S[P[i]]
    for i in range(1, len(S)):
        S[i] = temp[i]
 
# Function to apply Permutation P to Sequence S K number of times
def solve(S, P, K):
    while K:
        if K & 1:
            apply(S, P)
        apply(P, P)
        K >>= 1
 
if __name__ == "__main__":
    P = [0, 2, 3, 4, 1]
    S = [0, 2, 1, 3, 4]
    K = 2
    solve(S, P, K)
    print("New Sequence =", end=" ")
    for i in range(1, len(S)):
        print(S[i], end=" ")

                    

Output
New Sequence = 3 4 2 1 



Complexity Analysis:

  • Brute Force: O(N * K)
  • Binary Exponentiation: O(N * logK)

4. Compute Product of 2 very Large Numbers Modulo M:

If we have 2 very large number A and B and we need no compute (A * B) mod M but (A * B) in 64-bit integer, then we can use the concept of binary exponentiation to compute the product of these 2 numbers by adding A to the answer B times.

When we are calculating (A * B), we can have 3 possible positive values of B:

Case 1: If B = 0, whatever be the value of A, our result will be 0.
Case 2: If B is an even number, then instead of calculating (A * B) mod M , we can calculate (((A * 2) mod M) * B/2) mod M and the result will be same.
Case 3: If B is an odd number, then instead of calculating (A * B), we can calculate (A + A * (B-1)) mod M, which is same as case 2.

We can recursively follow the above steps to get our result.

Examples:

(25 * 10) mod 60 = ((25 * 2) mod 60 * 5) mod 60
= ((50 mod 60) * 5) mod 60
= (50 + (50 mod 60) * 4) mod 60
= (50 + (100 mod 60) * 2) mod 60
= (50 + (40 mod 60) * 2) mod 60
= (50 + (80 mod 60)) mod 60
= (50 + 20) mod 60
= 10

Therefore, we can compute (A * B) mod M using Binary Exponentiation:

C++

#include <bits/stdc++.h>
using namespace std;
 
const int mod = 1e9 + 7;
 
// function to multiply to very large numbers
int multiply(int A, int B) {
    int ans = 0;
    while(B) {
        if(B & 1) {
            ans = (ans + A) % mod;
        }
        A = (A + A) % mod;
        B >>= 1;
    }
    return ans;
}
 
int main() {
 
    int A = 1e9, B = 1e9;
    cout << multiply(A, B);
    return 0;
}

                    

Output
49



Complexity Analysis:

  • Brute Force: O(1), but not possible for large numbers
  • Binary Exponentiation: O(log B), as we have distributed the multiplication operation to a series of log(B) addition operations.

Practice Problems on Binary Exponentiation for Competitive Programming:

Easy Level Problems on Binary Exponentiation:

Problem

Problem Link

Padovan Sequence

Practice Now

Count ways to express N as the sum of 1, 3 and 4

Practice Now

Modified Fibonacci

Practice Now

Geometric Progression

Practice Now

Carol Numbers

Practice Now

Medium Level Problems on Binary Exponentiation:

Problem

Problem Link

Matrix Exponentiation

Practice Now

Challenge by Nikitasha

Practice Now

Left Most Divisor

Practice Now

Rahul and the Lift

Practice Now

Hard Level Problems on Binary Exponentiation:

Problem

Problem Link

nCr mod M

Practice Now

Generalized Fibonacci Numbers

Practice Now

Find the pattern

Practice Now

Related Article:



Last Updated : 24 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Similar Reads