The Wayback Machine - https://web.archive.org/web/20240829153821/https://www.geeksforgeeks.org/exponential-squaring-fast-modulo-multiplication/
Open In App

Exponential Squaring (Fast Modulo Multiplication)

Last Updated : 03 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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:

  1. Basic Method(Binary Exponentiation)
  2. 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

                    

Output
754573817

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.



Previous Article
Next Article

Similar Reads

Fast Fourier Transformation for polynomial multiplication
Given two polynomial A(x) and B(x), find the product C(x) = A(x)*B(x). There is already an O([Tex]n^2 [/Tex]) naive approach to solve this problem. here. This approach uses the coefficient form of the polynomial to calculate the product.A coefficient representation of a polynomial [Tex]A(x)=\sum_{j=0}^{n-1}a_jx^j [/Tex]is a = a0, a1, ..., an-1. Exa
13 min read
Iterative Fast Fourier Transformation for polynomial multiplication
Given two polynomials, A(x) and B(x), find the product C(x) = A(x)*B(x). In the previous post, we discussed the recursive approach to solve this problem which has O(nlogn) complexity. Examples: Input : A[] = {9, -10, 7, 6} B[] = {-5, 4, 0, -2} Output : C(x) = [Tex]-12x^6 -14x^5 +44x^4 -20x^3 - 75x^2 +86x -45[/Tex] In real-life applications such as
12 min read
Karatsuba Algorithm for fast Multiplication of Large Decimal Numbers represented as Strings
Given two numeric strings A and B, the task is to find the product of the two numeric strings efficiently. Example: Input: A = 5678, B = 1234Output: 7006652 Input: A = 74638463789, B = 35284567382Output: 2633585904851937530398 Approach: The given problem can be solved using Karastuba's Algorithm for Fast Multiplication, the idea is to append zeroes
15+ min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
Exponential notation of a decimal number
Given a positive decimal number, find the simple exponential notation (x = a·10^b) of the given number. Examples: Input : 100.0 Output : 1E2 Explanation: The exponential notation of 100.0 is 1E2. Input :19 Output :1.9E1 Explanation: The exponential notation of 16 is 1.6E1. Approach: The simplest way is to find the position of the first non zero dig
5 min read
Find the larger exponential among two exponentials
Given four integers A, B, C and D. The task is to find which is greater AB or CD. Examples: Input: A = 2, B = 5, C = 4, D = 2 Output: 2^5 25 = 32 42 = 16 Input: A = 8, B = 29, C = 60, D = 59 Output: 60^59 Naive approach: Calculate the values of AB and CD then compare them. This approach will fail when the values are greater say 562145321457. Effici
4 min read
Count of exponential paths in a Binary Tree
Given a Binary Tree, the task is to count the number of Exponential paths in the given Binary Tree. Exponential Path is a path where root to leaf path contains all nodes being equal to xy, &amp; where x is a minimum possible positive constant &amp; y is a variable positive integer. Example: Input: 27 / \ 9 81 / \ / \ 3 10 70 243 / \ 81 909 Output:
11 min read
Print all Exponential Levels of a Binary Tree
Given a Binary Tree, the task is to print all the Exponential Levels in the given Binary Tree. An Exponential Level is a level whose all nodes of that levels equals to xy, &amp; where x is a minimum possible positive constant &amp; y is a variable positive integer. Examples: Input: 20 / \ 9 81 / \ / \ 3 10 70 243 / \ 81 909 Output: 20 9 81 Explanat
15+ min read
Exponential factorial of N
Given a positive integer N, the task is to print the Exponential factorial of N. Since the output can be very large, print the answer modulus 1000000007. Examples: Input: N = 4 Output: 262144 Input: N = 3 Output: 9 Approach: The given problem can be solved based on the following observations: The exponential factorial is defined by the recurrence r
4 min read
Find all ranges of consecutive numbers from Array | Set -2 (using Exponential BackOff)
Given a sorted array arr[] consisting of N integers without any duplicates, the task is to find the ranges of consecutive numbers from that array. Examples: Input: arr[] = {1, 2, 3, 6, 7} Output: 1-&gt;3, 6-&gt;7 Explanation: There are two ranges of consecutive number from that array. Range 1 = 1 -&gt; 3 Range 2 = 6 -&gt; 7 Input: arr[] = {-1, 0, 1
11 min read
Exponential Search
The name of this searching algorithm may be misleading as it works in O(Log n) time. The name comes from the way it searches an element. Given a sorted array, and an element x to be searched, find position of x in the array. Input: arr[] = {10, 20, 40, 45, 55} x = 45 Output: Element found at index 3 Input: arr[] = {10, 15, 25, 45, 55} x = 15 Output
15+ min read
Exponential value sort
Given a sorted array arr[] and an integer P. Your task is to raise elements of arr[] to power of P and return them in sorted order in a new array. Examples:Input: arr[] = {-20, -5, 1, 2, 8}, P=2Output: 1 4 25 64 400Explanation: When we square the values of arr we get 400,25,1,4,64 which then sorted will give us the values as [1,4,25,64,400]. We hav
8 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Difference Between Exponential and Polynomial Complexities
Understanding the computational complexity of algorithms is essential in computer science, as it helps determine the feasibility and efficiency of solutions to problems. Two of the most common types of complexities are exponential and polynomial complexities. This article will provided the differences between these two, explaining their characteris
4 min read
How does Floyd's slow and fast pointers approach work?
We have discussed Floyd's fast and slow pointer algorithms in Detect loop in a linked list. The algorithm is to start two pointers, slow and fast from head of linked list. We move slow one node at a time and fast two nodes at a time. If there is a loop, then they will definitely meet. This approach works because of the following facts. 1) When slow
9 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Setting up Sublime Text For Competitive Programming (C++) Using Fast Olympic Coding Plugin
Competitive Programming is a mind sport where time matters the most. For that, a fast and easy-to-use tool is required for writing code. Sublime text along with the CppFastOlympicCoding plugin provides the same. Sublime text is popular for its fast performance and aesthetic UI. The CppFastOlympicCoding plugin offers features such as: TestManager: W
4 min read
Fast convolution for 64-bit integers
Convolution is a mathematical operation used in signal processing, image processing, and other fields to combine two functions in order to produce a third function. It is defined as the integral of the product of two functions, one of which is flipped and shifted over time. It is often represented using the symbol "*" and is useful for filtering, s
7 min read
Python | Inverse Fast Fourier Transformation
Inverse Fast Fourier transform (IDFT) is an algorithm to undoes the process of DFT. It is also known as backward Fourier transform. It converts a space or time signal to a signal of the frequency domain. The DFT signal is generated by the distribution of value sequences to different frequency components. Working directly to convert on Fourier trans
2 min read
Fast method to calculate inverse square root of a floating point number in IEEE 754 format
Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.A simple solution is to do floating point arithmetic. Following is an example function. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; float InverseSquareRoot(float x) { return 1/sqrt(x); } int main() { cou
4 min read
Fast I/O in Java in Competitive Programming
Using Java in competitive programming is not something many people would suggest just because of its slow input and output, and well indeed it is slow. In this article, we have discussed some ways to get around the difficulty and change the verdict from TLE to (in most cases) AC. Example: Input: 7 3 1 51 966369 7 9 999996 11 Output: 41. Scanner Cla
7 min read
Ropes Data Structure (Fast String Concatenation)
One of the most common operations on strings is appending or concatenation. Appending to the end of a string when the string is stored in the traditional manner (i.e. an array of characters) would take a minimum of O(n) time (where n is the length of the original string). We can reduce time taken by append using Ropes Data Structure. Ropes Data Str
15+ min read
Fast average of two numbers without division
Given two numbers, find floor of their average without using division. Input : x = 10, y = 12Output : 11Input : x = 10, y = 7Output : 8We take floor of sum.The idea is to use right shift operator, instead of doing (x + y)/2, we do (x + y) &gt;&gt; 1 [GFGTABS] C++ // C++ program to find average without using // division. #include &lt;bits/stdc++.h
3 min read
Fast I/O for Competitive Programming
In competitive programming, it is important to read input as fast as possible so we save valuable time. You must have seen various problem statements saying: " Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)" . The key for such problems is to use Faster I/O techniques. It is of
4 min read
Segment Trees | (Product of given Range Modulo m)
Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the product of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1 take its modulus by an integer m.2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i
15+ min read
Equalizing array using increment under modulo 3
Given an array A containing N non-negative integers. Only following operation can be performed on the array: A[i] = ( A[i] + 1 ) % 3 where A[i] is the element of array A at index i, and performing this operation once costs 1 unit. Find the minimum cost to make all elements equal. Examples : Input : 1 0 3 2 Output : 4 units Explanation: First 3 is c
14 min read
Divisibility by 3 where each digit is the sum of all prefix digits modulo 10
Given K, number of digits, and d0 and d1 as the two digits to form the k-sized integer. Task is to check whether the k-sized number formed using d0 and d1 is divisible by 3 or not. For each i, di is the sum of all preceding (more significant) digits, modulo 10 — more formally, the following formula must hold : [Tex]\huge{d_{i} = \sum_{j = 0}^{i - 1
11 min read
Modulo power for large numbers represented as strings
Given two numbers sa and sb represented as strings, find ab % MOD where MOD is 1e9 + 7. The numbers a and b can contain upto 106 digits.Examples: Input : sa = 2, sb = 3 Output : 8Input : sa = 10000000000000000000000000000000000000000000 sb = 10000000000000000000000000000000000000000000 Output : 494234546 As a and b very large (may contain upto 10^6
9 min read
Longest subarray with elements having equal modulo K
Given an integer K and an array arr of integer elements, the task is to print the length of the longest sub-array such that each element of this sub-array yields same remainder upon division by K. Examples: Input: arr[] = {2, 1, 5, 8, 1}, K = 3 Output: 2 {2, 1, 5, 8, 1} gives remainders {2, 1, 2, 2, 1} on division with 3 Hence, longest sub-array le
10 min read