The Wayback Machine - https://web.archive.org/web/20240906205715/https://www.geeksforgeeks.org/compute-power-of-power-k-times-m/
Open In App

Compute power of power k times % m

Last Updated : 24 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given x, k and m. Compute (xxxx…k)%m, x is in power k times. Given x is always prime and m is greater than x. 

Examples: 

Input : 2 3 3
Output : 1
Explanation : ((2 ^ 2) ^ 2) % 3 
           = (4 ^ 2) % 3 
           = 1

Input : 3 2 3
Output : 0
Explanation : (3^3)%3 = 0

A naive approach is to compute the power of x k times and do modulus operation every time.  

C++




// C++ program for computing
// x^x^x^x.. %m
#include <bits/stdc++.h>
using namespace std;
 
// Function to compute the given value
int calculate(int x, int k, int m)
{
    int result = x;
    k--;
 
    // compute power k times
    while (k--) {
        result = pow(result, x);
 
        if (result > m)
            result %= m;
    }
 
    return result;
}
 
// Driver Code
int main()
{
    int x = 5, k = 2, m = 3;
 
    // Calling function
    cout << calculate(x, k, m);
 
    return 0;
}


C




// C program for computing
// x^x^x^x.. %m
#include <stdio.h>
#include <math.h>
 
// Function to compute the given value
int calculate(int x, int k, int m)
{
    int result = x;
    k--;
 
    // compute power k times
    while (k--) {
        result = pow(result, x);
 
        if (result > m)
            result %= m;
    }
 
    return result;
}
 
// Driver Code
int main()
{
    int x = 5, k = 2, m = 3;
 
    // Calling function
    printf("%d",calculate(x, k, m));
 
    return 0;
}
 
// This code is contributed by kothavvsaakash.


Java




// Java program for computing
// x^x^x^x.. %m
class GFG
{
 
// Function to compute
// the given value
static int calculate(int x,
                     int k, int m)
{
    int result = x;
    k--;
 
    // compute power k times
    while (k --> 0)
    {
        result = (int)Math.pow(result, x);
 
        if (result > m)
            result %= m;
    }
 
    return result;
}
 
// Driver Code
public static void main(String args[])
{
    int x = 5, k = 2, m = 3;
 
    // Calling function
    System.out.println( calculate(x, k, m));
}
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program for
# computing x^x^x^x.. %m
import math
 
# Function to compute
# the given value
def calculate(x, k, m):
    result = x;
    k = k - 1;
     
    # compute power k times
    while (k):
        result = math.pow(result, x);
        if (result > m):
            result = result % m;
        k = k - 1;
    return int(result);
 
# Driver Code
x = 5;
k = 2;
m = 3;
 
# Calling function
print(calculate(x, k, m));
     
# This code is contributed
# by mits


C#




// C# program for computing
// x^x^x^x.. %m
using System;
 
class GFG
{
     
// Function to compute
// the given value
static int calculate(int x,
                     int k,
                     int m)
{
    int result = x;
    k--;
 
    // compute power
    // k times
    while (k --> 0)
    {
        result = (int)Math.Pow(result, x);
 
        if (result > m)
            result %= m;
    }
 
    return result;
}
 
// Driver Code
static public void Main ()
{
    int x = 5, k = 2, m = 3;
 
    // Calling function
    Console.WriteLine(
            calculate(x, k, m));
}
}
 
// This code is contributed
// by ajit


PHP




<?php
// PHP program for computing
// x^x^x^x.. %m
 
// Function to compute
// the given value
function calculate($x, $k, $m)
{
    $result = $x;
    $k--;
 
    // compute power k times
    while ($k--)
    {
        $result = pow($result, $x);
 
        if ($result > $m)
            $result %= $m;
    }
 
    return $result;
}
 
// Driver Code
$x = 5;
$k = 2;
$m = 3;
 
// Calling function
echo calculate($x, $k, $m);
     
// This code is contributed
// by akt_mit
?>


Javascript




<script>
//program for computing
// x^x^x^x.. %m
 
// Function to compute
// the given value
function calculate(x, k, m)
{
    let result = x;
    k = k - 1;
 
    // compute power k times
    while (k--)
    {
        result = Math.pow(result, x);
 
        if (result > m)
            result %= m;
    }
 
    return result;
}
 
// Driver Code
let x = 5;
let k = 2;
let m = 3;
 
// Calling function
document.write(calculate(x, k, m));
     
// This code is contributed
// by sravan kumar
</script>


Output: 

2

 

Time Complexity: O(k * logx), where k and x represents the value of the given integers.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
 

An efficient solution is to use Euler’s Totient Function to solve this problem. Since x is a prime number and is always greater than m, that means x and m will always be co-prime. So the fact that will help here is (a^b)%m = (a^(b % et(m)))%m, where et(m) is Euler Totient Function. Consider having a function calculate(x, k, m) that gives the value (x^x^x^x…k times)%m. (x^x^x^x…k times)%m can be written as (a^b)%m = (a^(b % et(m)))%m, where b = calculate(x, k-1, et(m)). A recursive function can be written, with the base cases when k=0 then, answer is 1, and if m=1, then answer is 0. 

Below is the implementation of the above approach. 

C++




// C++ program to compute
// x^x^x^x.. %m
#include <bits/stdc++.h>
using namespace std;
const int N = 1000000;
 
// Create an array to store
// phi or totient values
long long phi[N + 5];
 
// Function to calculate Euler
// Totient values
void computeTotient()
{
    // indicates not evaluated yet
    // and initializes for product
    // formula.
    for (int i = 1; i <= N; i++)
        phi[i] = i;
 
    // Compute other Phi values
    for (int p = 2; p <= N; p++) {
 
        // If phi[p] is not computed already,
        // then number p is prime
        if (phi[p] == p) {
 
            // Phi of a prime number p is
            // always equal to p-1.
            phi[p] = p - 1;
 
            // Update phi values of all
            // multiples of p
            for (int i = 2 * p; i <= N; i += p) {
 
                // Add contribution of p to its
                // multiple i by multiplying with
                // (1 - 1/p)
                phi[i] = (phi[i] / p) * (p - 1);
            }
        }
    }
}
 
// Iterative Function to calculate (x^y)%p in O(log y)
long long power(long long x, long long y, long long p)
{
    long long res = 1; // Initialize result
 
    x = x % p; // Update x if it is more than or
    // equal to p
 
    while (y > 0) {
 
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Function to calculate
// (x^x^x^x...k times)%m
long long calculate(long long x, long long k,
                    long long mod)
{
    // to store different mod values
    long long arr[N];
 
    long long count = 0;
 
    while (mod > 1) {
        arr[count++] = mod;
        mod = phi[mod];
    }
 
    long long result = 1;
    long long loop = count + 1;
    arr[count] = 1;
 
    // run loop in reverse to calculate
    // result
    for (int i = min(k, loop) - 1; i >= 0; i--)
        result = power(x, result, arr[i]);
 
    return result;
}
 
// Driver Code
int main()
{
    // compute euler totient function values
    computeTotient();
 
    long long x = 3, k = 2, m = 3;
 
    // Calling function to compute answer
    cout << calculate(x, k, m) << endl;
 
    return 0;
}


C




// C program to compute
// x^x^x^x.. %m
#include <stdio.h>
 
#define N 1000000
 
// Create an array to store
// phi or totient values
long long phi[N + 5];
 
// Function to calculate Euler
// Totient values
 
int min(int a, int b)
{
  int min = a;
  if(min > b)
    min = b;
  return min;
}
 
void computeTotient()
{
    // indicates not evaluated yet
    // and initializes for product
    // formula.
    for (int i = 1; i <= N; i++)
        phi[i] = i;
 
    // Compute other Phi values
    for (int p = 2; p <= N; p++) {
 
        // If phi[p] is not computed already,
        // then number p is prime
        if (phi[p] == p) {
 
            // Phi of a prime number p is
            // always equal to p-1.
            phi[p] = p - 1;
 
            // Update phi values of all
            // multiples of p
            for (int i = 2 * p; i <= N; i += p) {
 
                // Add contribution of p to its
                // multiple i by multiplying with
                // (1 - 1/p)
                phi[i] = (phi[i] / p) * (p - 1);
            }
        }
    }
}
 
// Iterative Function to calculate (x^y)%p in O(log y)
long long power(long long x, long long y, long long p)
{
    long long res = 1; // Initialize result
 
    x = x % p; // Update x if it is more than or
    // equal to p
 
    while (y > 0) {
 
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Function to calculate
// (x^x^x^x...k times)%m
long long calculate(long long x, long long k,
                    long long mod)
{
    // to store different mod values
    long long arr[N];
 
    long long count = 0;
 
    while (mod > 1) {
        arr[count++] = mod;
        mod = phi[mod];
    }
 
    long long result = 1;
    long long loop = count + 1;
    arr[count] = 1;
 
    // run loop in reverse to calculate
    // result
    for (int i = min(k, loop) - 1; i >= 0; i--)
        result = power(x, result, arr[i]);
 
    return result;
}
 
// Driver Code
int main()
{
    // compute euler totient function values
    computeTotient();
 
    long long x = 3, k = 2, m = 3;
 
    // Calling function to compute answer
    printf("%lld\n",calculate(x, k, m));
 
    return 0;
}
 
// This code is contributed by kothavvsaakash.


Java




// Java program for computing
// x^x^x^x.. %m
class GFG
{
 
// Create an array to store
// phi or totient values
static int N = 1000000;
static long phi[] = new long[N + 5];
 
// Function to calculate
// Euler Totient values
static void computeTotient()
{
    // indicates not evaluated
    // yet and initializes for
    // product formula.
    for (int i = 1; i <= N; i++)
        phi[i] = i;
 
    // Compute other Phi values
    for (int p = 2; p <= N; p++)
    {
 
        // If phi[p] is not
        // computed already,
        // then number p is prime
        if (phi[p] == p)
        {
 
            // Phi of a prime number p
            // is always equal to p-1.
            phi[p] = p - 1;
 
            // Update phi values of
            // all multiples of p
            for (int i = 2 * p; i <= N; i += p)
            {
 
                // Add contribution of p
                // to its multiple i by
                // multiplying with (1 - 1/p)
                phi[i] = (phi[i] / p) *
                              (p - 1);
            }
        }
    }
}
 
// Iterative Function to
// calculate (x^y)%p in O(log y)
static long power(long x, long y, long p)
{
    long res = 1; // Initialize result
 
    x = x % p; // Update x if it is
               // more than or equal to p
 
    while (y > 0)
    {
 
        // If y is odd, multiply
        // x with result
        if ((y & 1) > 0)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Function to calculate
// (x^x^x^x...k times)%m
static long calculate(long x, long k,
                      long mod)
{
    // to store different
    // mod values
    long arr[] = new long[N];
 
    long count = 0;
 
    while (mod > 1)
    {
        arr[(int)count++] = mod;
        mod = phi[(int)mod];
    }
 
    long result = 1;
    long loop = count + 1;
    arr[(int)count] = 1;
 
    // run loop in reverse
    // to calculate result
    for (int i = (int)Math.min(k, loop) - 1;
                                i >= 0; i--)
        result = power(x, result, arr[i]);
 
    return result;
}
 
// Driver Code
public static void main(String args[])
{
    // compute euler totient
    // function values
    computeTotient();
 
    long x = 3, k = 2, m = 3;
 
    // Calling function
    // to compute answer
    System.out.println(calculate(x, k, m));
}
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program to compute
# x^x^x^x.. %m
 
N = 1000000
 
# Create an array to store
# phi or totient values
phi=[0 for i in range(N + 5)]
 
# Function to calculate Euler
# Totient values
def computeTotient():
    # indicates not evaluated yet
    # and initializes for product
    # formula.
    for i in range(1, N+1):
        phi[i] = i
 
    # Compute other Phi values
    for p in range(2, N+1):
 
        # If phi[p] is not computed already,
        # then number p is prime
        if (phi[p] == p):
 
            # Phi of a prime number p is
            # always equal to p-1.
            phi[p] = p - 1
 
            # Update phi values of all
            # multiples of p
            for i in range(2*p, N+1, p):
 
                # Add contribution of p to its
                # multiple i by multiplying with
                # (1 - 1/p)
                phi[i] = (phi[i] // p) * (p - 1)
 
 
# Iterative Function to calculate (x^y)%p in O(log y)
def power(x, y, p):
    res = 1 # Initialize result
 
    x = x % p # Update x if it is more than or
    # equal to p
 
    while (y > 0):
 
        # If y is odd, multiply x with result
        if (y & 1):
            res = (res * x) % p
 
        # y must be even now
        y = y >> 1 # y = y/2
        x = (x * x) % p
 
    return res
 
 
# Function to calculate
# (x^x^x^x...k times)%m
def calculate(x, k,mod):
    # to store different mod values
    arr=[0 for i in range(N)]
 
    count = 0
 
    while (mod > 1):
        arr[count] = mod
        count+=1
        mod = phi[mod]
 
    result = 1
    loop = count + 1
    arr[count] = 1
 
    # run loop in reverse to calculate
    # result
    for i in range(min(k,loop),-1,-1):
        result = power(x, result, arr[i])
 
    return result
 
# Driver Code
 
# compute euler totient function values
computeTotient()
 
x = 3
k = 2
m = 3
 
# Calling function to compute answer
print(calculate(x, k, m))
 
# This code is contributed by mohit kumar 29


C#




// C# program for computing
// x^x^x^x.. %m
using System;
 
class GFG
{
     
// Create an array to store
// phi or totient values
static int N = 1000000;
static long []phi = new long[N + 5];
 
// Function to calculate
// Euler Totient values
static void computeTotient()
{
    // indicates not evaluated
    // yet and initializes for
    // product formula.
    for (int i = 1; i <= N; i++)
        phi[i] = i;
 
    // Compute other Phi values
    for (int p = 2; p <= N; p++)
    {
 
        // If phi[p] is not
        // computed already,
        // then number p is prime
        if (phi[p] == p)
        {
 
            // Phi of a prime
            // number p is
            // always equal
            // to p-1.
            phi[p] = p - 1;
 
            // Update phi values
            // of all multiples
            // of p
            for (int i = 2 * p;
                     i <= N; i += p)
            {
 
                // Add contribution of p
                // to its multiple i by
                // multiplying with (1 - 1/p)
                phi[i] = (phi[i] / p) *
                              (p - 1);
            }
        }
    }
}
 
// Iterative Function to
// calculate (x^y)%p in O(log y)
static long power(long x,
                  long y, long p)
{
    long res = 1; // Initialize result
 
    x = x % p; // Update x if it 
               // is more than or
               // equal to p
 
    while (y > 0)
    {
 
        // If y is odd, multiply
        // x with result
        if ((y & 1) > 0)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Function to calculate
// (x^x^x^x...k times)%m
static long calculate(long x, long k,
                      long mod)
{
    // to store different
    // mod values
    long []arr = new long[N];
 
    long count = 0;
 
    while (mod > 1)
    {
        arr[(int)count++] = mod;
        mod = phi[(int)mod];
    }
 
    long result = 1;
    long loop = count + 1;
    arr[(int)count] = 1;
 
    // run loop in reverse
    // to calculate result
    for (int i = (int)Math.Min(k, loop) - 1;
                                i >= 0; i--)
        result = power(x, result,
                          arr[i]);
 
    return result;
}
 
// Driver Code
static public void Main ()
{
     
// compute euler totient
// function values
computeTotient();
 
long x = 3, k = 2, m = 3;
 
// Calling function
// to compute answer
Console.WriteLine(calculate(x, k, m));
}
}
 
// This code is contributed
// by akt_mit


Javascript




<script>
    // Javascript program for computing x^x^x^x.. %m
     
    // Create an array to store
    // phi or totient values
    let N = 1000000;
    let phi = new Array(N + 5);
    phi.fill(0);
 
    // Function to calculate
    // Euler Totient values
    function computeTotient()
    {
        // indicates not evaluated
        // yet and initializes for
        // product formula.
        for (let i = 1; i <= N; i++)
            phi[i] = i;
 
        // Compute other Phi values
        for (let p = 2; p <= N; p++)
        {
 
            // If phi[p] is not
            // computed already,
            // then number p is prime
            if (phi[p] == p)
            {
 
                // Phi of a prime number p
                // is always equal to p-1.
                phi[p] = p - 1;
 
                // Update phi values of
                // all multiples of p
                for (let i = 2 * p; i <= N; i += p)
                {
 
                    // Add contribution of p
                    // to its multiple i by
                    // multiplying with (1 - 1/p)
                    phi[i] = (phi[i] / p) * (p - 1);
                }
            }
        }
    }
 
    // Iterative Function to
    // calculate (x^y)%p in O(log y)
    function power(x, y, p)
    {
        let res = 1; // Initialize result
 
        x = x % p; // Update x if it is
                   // more than or equal to p
 
        while (y > 0)
        {
 
            // If y is odd, multiply
            // x with result
            if ((y & 1) > 0)
                res = (res * x) % p;
 
            // y must be even now
            y = y >> 1; // y = y/2
            x = (x * x) % p;
        }
        return res;
    }
 
    // Function to calculate
    // (x^x^x^x...k times)%m
    function calculate(x, k, mod)
    {
        // to store different
        // mod values
        let arr = new Array(N);
        arr.fill(0);
 
        let count = 0;
 
        while (mod > 1)
        {
            arr[count++] = mod;
            mod = phi[mod];
        }
 
        let result = 1;
        let loop = count + 1;
        arr[count] = 1;
 
        // run loop in reverse
        // to calculate result
        for (let i = Math.min(k, loop) - 1; i >= 0; i--)
            result = power(x, result, arr[i]);
 
        return result;
    }
     
    // compute euler totient
    // function values
    computeTotient();
  
    let x = 3, k = 2, m = 3;
  
    // Calling function
    // to compute answer
    document.write(calculate(x, k, m));
 
// This code is contributed by rameshtravel07.
</script>


Output: 

0

 

Time Complexity: O(N), where N is 106 since all the Euler Totient values are pre-calculated. 
Auxiliary Space: O(N), where N is 106



Previous Article
Next Article

Similar Reads

Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
Given three integers X, Y and Z, the task is to find the sum of all the numbers formed having 4 at most X times, 5 at most Y times, and 6 at most Z times, under mod 10^9+7.Examples: Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 Input: X = 4, Y = 5, Z = 6 Outpu
9 min read
Compute modulus division by a power-of-2-number
Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number. Input: 6 4 Output: 2 Explanation: As 6%4 = 2 Input: 12 8 Output: 4 Explanation: As 12%8 = 4 Input: 10 2 Output: 0 Explanation:As 10%2 = 0 Let ith bit from right is set in d. For getting n modulus d, we just need to return 0 to i-1 (from right) bits of n
6 min read
Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
Given an array arr[], the task is to count unordered pairs of positive integers (p, q) such that p occurs in the array at least q times and q occurs at least p times. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 (1, 1) is the only valid pair. Input: arr[] = {3, 3, 2, 2, 2} Output: 2 (2, 3) and (2, 2) are the only possible pairs. Approach: The
8 min read
Build a DFA to accept a binary string containing "01" i times and "1" 2j times
Given a binary string str, the task is to build a DFA that accepts given binary string if it contains "01" i times and "1" 2j times, i.e., [Tex]L={(01)^i (1)^{2j} \text{ where }i\geq1\text{ and }j\geq1} [/Tex] Examples: Input: str = "011111" Output: Accepted Explanation: The string follows the language as: (01)1(1)2*2 Input: str = "01111" Output: N
9 min read
Lexicographically Kth-smallest string having 'a' X times and 'b' Y times
Given three non-negative integers, X, Y, and K, the task is to find the Kth smallest lexicographical string having X occurrences of character 'a' and Y occurrences of character 'b'. Examples: Input: X = 2, Y = 3, K = 3Output: abbabExplanation: First lexicographical smallest string = "aabbb".Second lexicographical smallest string = "ababb".Third lex
15+ min read
Find character at Kth index by appending S1 (M) times and S2 (M+1) times
Given two strings, S1 and S2 and an integer K.A string str can be made by performing the following operations: Take an Empty String InitiallyAppend S1 one timesAppend S2 two timesAppend S1 three timesAppend S2 four timesAppend S1 five timesAppend S2 six timesYou can keep building this string until it reaches K The task is to find the character at t
15 min read
Shortest String formed by concatenating string A x times and B y times such that n(A)*x = n(B)*y
Given two strings A and B, the task is to find the shortest string which is some multiple of both A and B. A string X is said to be a multiple of string Y if string X can be formed by the concatenation of multiple occurrences of string Y. Example: Input: A = "aaa", B= "aa"Output: aaaaaaExplanation: Multiplying A two times and B three times will res
7 min read
Count of Subarray with B times Sum equal to C times Length
Given, an array A[] of N integers, and also given two positive integers B and C, the task is to find the number of subarrays, such that B* Sum of elements of the subarray = C * Length of the subarray (here * describes multiplication). Examples: Input: N = 3, A[] = {3, -1, 1}, B = 1, C = 1Output: 3Explanation: The subarrays satisfying the conditions
7 min read
Compute the minimum or maximum of two integers without branching
On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching. C/C++ Code /* The obvious approach to find minimum (involves branching) */ int min(int x, int y) { return (x &lt; y) ? x : y } //This code is contributed by Shubham Singh Java Code /* The obvious approach to find minimum
11 min read
Program to compute division upto n decimal places
Given 3 numbers x, y and n compute the division (x/y) upto n decimal places. Examples : Input : x = 22, y = 7, n = 10Output : 3.1428571428Explanation : Since n = 10, division (x / y) is taken till 10 decimal places. Input : x = 22, y = 7, n = 20Output : 3.14285714285714285714 Approach : Get the remainder and get it subtracted by the dividend, multi
7 min read
Compute maximum of the function efficiently over all sub-arrays
Given an array, arr[] and a function F(i, j). The task is to compute max{F(i, j)} over all sub-arrays [i..j].The function F() is defined as: [Tex]F(l, r) = \sum_{i = l}^{r - 1} |arr[i] - arr[i+1]|.(-1)^{i-l}[/Tex] Examples: Input : arr[] = { 1, 5, 4, 7 } Output : 6 Values of F(i, j) for all the sub-arrays: { 1, 5 } = |1 - 5| * (1) = 4 { 1, 5, 4 } =
7 min read
Program to compute log a to any base b (logb a)
Given two integers a and b, the task is to find the log of a to any base b, i.e. logb a.Examples: Input: a = 3, b = 2Output: 1Input: a = 256, b = 4Output: 4Recommended: Please try your approach on {IDE} first, before moving on to the solution.Using inbuilt log2 function Find the log of a to the base 2 with the help of log2() method Find the log of
8 min read
Javascript Program to Efficiently compute sums of diagonals of a matrix
Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix. A00 A01 A02 A03 A10 A11 A12 A13 A20 A21 A22 A23 A30 A31 A32 A33 The primary diagonal is formed by the elements A00, A11, A22, A33. Condition for Principal Diagonal: The row-column condition is row = column
3 min read
Compute before Matrix
For a given matrix before[][], the corresponding cell (x, y) of the after[][] matrix is calculated as follows: res = 0;for(i = 0; i &lt;= x; i++){ for( j = 0; j &lt;= y; j++){ res += before(i, j); }}after(x, y) = res; Given an N*M matrix after[][], your task is to find the corresponding before[][] matrix for the given matrix. Examples: Input: N = 2
9 min read
Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem)
Given three numbers n, r and p, the task is to compute the value of nCr % p. Note: p is a square-free number and the largest prime factor of p ≤ 50. Examples: Input: n = 10, r = 2, p = 13Output: 6Explanation: 10C2 is 45 and 45 % 13= 6 Input: n = 6, r = 2, p = 13Output: 2 Approach: We have already discussed several other approaches of this problem.
10 min read
Compute AND value by doing XOR of given arrays
Given two arrays A[] and B[], the array C[] is formed by the XOR of ai and bi, i.e ci = ai^bi, the task is to find the maximum AND value of all the array elements of C given that A and B can be permuted in any way. Examples: Input: A[] ={1, 0, 0, 3, 3}, B[] = {2, 3, 2, 1, 0}Output: 2Explanation: C [] = {3, 3, 2, 2, 3} on doing AND of array C value
13 min read
Efficient Program to Compute Sum of Series 1/1! + 1/2! + 1/3! + 1/4! + .. + 1/n!
Given a positive integer n, write a function to compute the sum of the series 1/1! + 1/2! + .. + 1/n!A Simple Solution is to initialize the sum as 0, then run a loop and call the factorial function inside the loop. Following is the implementation of a simple solution. C/C++ Code // A simple C++ program to compute sum of series 1/1! + 1/2! + .. + 1/
7 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 (mod a) * 10) + (y (mod a))) mod a where, x : left
4 min read
Compute nCr%p using Lucas Theorem
Given three numbers n, r and p, compute the value of nCr mod p. Examples: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 1000, r = 900, p = 13 Output: 8 We strongly recommend referring below post as a prerequisite of this.Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)We have intr
12 min read
Compute n! under modulo p
Given a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally ne
15+ min read
Introduction and Dynamic Programming solution to compute nCr%p
Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is to first compute nCr, then compute nCr % p. This s
15+ min read
Compute nCr%p using Fermat Little Theorem
Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2Recommended PracticenCrTry It! We have discussed the following methods in previous po
15+ min read
Compute the parity of a number using XOR and table look-up
Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits. 1 --&gt; parity of the set is odd 0 --&gt; parity of the set is even Examples: Input : 254 Output : Odd Parity Explanation : Binary of 254 is 11
9 min read
Efficiently compute sums of diagonals of a matrix
Given a 2D square matrix, find the sum of elements in Principal and Secondary diagonals. For example, consider the following 4 X 4 input matrix. A00 A01 A02 A03 A10 A11 A12 A13 A20 A21 A22 A23 A30 A31 A32 A33 The primary diagonal is formed by the elements A00, A11, A22, A33. Condition for Principal Diagonal: The row-column condition is row = column
10 min read
Compute (a*b)%c such that (a%c) * (b%c) can be beyond range
Given three numbers a, b and c such that a, b and c can be at most 1016. The task is to compute (a*b)%c A simple solution of doing ( (a % c) * (b % c) ) % c would not work here. The problem here is that a and b can be large so when we calculate (a % c) * (b % c), it goes beyond the range that long long int can hold, hence overflow occurs. For examp
8 min read
Compute the integer absolute value (abs) without branching
We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 2's complement form, to get the absolute value of a negative number we have to toggle bits of the number and add 1 to the result.For example -2 in a 8 bit system is stored as follows 1 1 1 1 1 1 1 0 where leftmost bit is
7 min read
Compute average of two numbers without overflow
Given two numbers A and B, such that 0 &lt;= A &lt;= B &lt;= (231 - 1). Compute the average ((A + B) / 2) of the two numbers. Examples: Input: A = 1000000000, B = 2000000000Output: 1500000000.000000Explanation: (A + B)/2 = (1000000000+ 2000000000)/2 = 1500000000.000000 Input: A = 2000000000, B = 2000000001Output: 2000000000.500000Explanation: (A +
5 min read
Compute sum of digits in all numbers from 1 to n
Given a number n, find the sum of digits in all numbers from 1 to n. Examples: Input: n = 5Output: Sum of digits in numbers from 1 to 5 = 15Input: n = 12Output: Sum of digits in numbers from 1 to 12 = 51Input: n = 328Output: Sum of digits in numbers from 1 to 328 = 3241Naive Solution: A naive solution is to go through every number x from 1 to n and
15+ min read
Check if given number is a power of d where d is a power of 2
Given an integer n, find whether it is a power of d or not, where d is itself a power of 2.Examples: Input : n = 256, d = 16 Output : Yes Input : n = 32, d = 16 Output : No Method 1 Take log of the given number on base d, and if we get an integer then number is power of d. C/C++ Code // CPP program to find if a number is power // of d where d is po
9 min read
Larger of a^b or b^a (a raised to power b or b raised to power a)
Given two numbers [Tex]$a and b$ [/Tex], find which is greater [Tex]a^b or \, b^a [/Tex].If [Tex]a^b &gt; b^a [/Tex], print a^b is greater If [Tex]a^b &lt; b^a [/Tex], print b^a is greater If [Tex]a^b = b^a [/Tex], print Both are equalExamples: Input : 3 5 Output : a^b is greater 3^5 = 243, 5^3 = 125. Since, 243&gt;125, therefore a^b &gt; b^a. Inpu
5 min read