Introduction and Dynamic Programming solution to compute nCr%p
Last Updated :
23 Apr, 2023
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.
METHOD 1: (Using Dynamic Programming)
A Simple Solution is to first compute nCr, then compute nCr % p. This solution works fine when the value of nCr is small.
What if the value of nCr is large?
The value of nCr%p is generally needed for large values of n when nCr cannot fit in a variable, and causes overflow. So computing nCr and then using modular operator is not a good idea as there will be overflow even for slightly larger values of n and r. For example the methods discussed here and here cause overflow for n = 50 and r = 40.
The idea is to compute nCr using below formula
C(n, r) = C(n-1, r-1) + C(n-1, r)
C(n, 0) = C(n, n) = 1
Working of Above formula and Pascal Triangle:
Let us see how above formula works for C(4, 3)
1==========>> n = 0, C(0, 0) = 1
1–1========>> n = 1, C(1, 0) = 1, C(1, 1) = 1
1–2–1======>> n = 2, C(2, 0) = 1, C(2, 1) = 2, C(2, 2) = 1
1–3–3–1====>> n = 3, C(3, 0) = 1, C(3, 1) = 3, C(3, 2) = 3, C(3, 3)=1
1–4–6–4–1==>> n = 4, C(4, 0) = 1, C(4, 1) = 4, C(4, 2) = 6, C(4, 3)=4, C(4, 4)=1
So here every loop on i, builds i’th row of pascal triangle, using (i-1)th row
Extension of above formula for modular arithmetic:
We can use distributive property of modular operator to find nCr % p using above formula.
C(n, r)%p = [ C(n-1, r-1)%p + C(n-1, r)%p ] % p
C(n, 0) = C(n, n) = 1
The above formula can be implemented using Dynamic Programming using a 2D array.
The 2D array based dynamic programming solution can be further optimized by constructing one row at a time. See Space optimized version in below post for details.
Binomial Coefficient using Dynamic Programming
Below is implementation based on the space optimized version discussed in above post.
C++
// A Dynamic Programming based solution to compute nCr % p
#include <bits/stdc++.h>
using namespace std;
// Returns nCr % p
int nCrModp(int n, int r, int p)
{
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// The array C is going to store last row of
// pascal triangle at the end. And last entry
// of last row is nCr
int C[r + 1];
memset(C, 0, sizeof(C));
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// Driver program
int main()
{
int n = 10, r = 2, p = 13;
cout << "Value of nCr % p is " << nCrModp(n, r, p);
return 0;
}
JAVA
// A Dynamic Programming based
// solution to compute nCr % p
import java.io.*;
import java.util.*;
import java.math.*;
class GFG {
// Returns nCr % p
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// Driver program
public static void main(String args[])
{
int n = 10, r = 2, p = 13;
System.out.println("Value of nCr % p is "
+ nCrModp(n, r, p));
}
}
// This code is contributed by Nikita Tiwari.
Python3
# A Dynamic Programming based solution to compute nCr % p
# Returns nCr % p
def nCrModp(n, r, p):
# Optimization for the cases when r is large
# compared to n-r
if (r > n- r):
r = n - r
# The array C is going to store last row of
# pascal triangle at the end. And last entry
# of last row is nCr.
C = [0 for i in range(r + 1)]
C[0] = 1 # Top row of Pascal Triangle
# One by constructs remaining rows of Pascal
# Triangle from top to bottom
for i in range(1, n + 1):
# Fill entries of current row
# using previous row values
for j in range(min(i, r), 0, -1):
# nCj = (n - 1)Cj + (n - 1)C(j - 1)
C[j] = (C[j] + C[j-1]) % p
return C[r]
# Driver Program
n = 10
r = 2
p = 13
print('Value of nCr % p is', nCrModp(n, r, p))
# This code is contributed by Soumen Ghosh
C#
// A Dynamic Programming based
// solution to compute nCr % p
using System;
class GFG {
// Returns nCr % p
static int nCrModp(int n, int r, int p)
{
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int[] C = new int[r + 1];
for (int i = 0; i < r + 1; i++)
C[i] = 0;
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows
// of Pascal Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using
// previous row values
for (int j = Math.Min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// Driver program
public static void Main()
{
int n = 10, r = 2, p = 13;
Console.Write("Value of nCr % p is "
+ nCrModp(n, r, p));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// A Dynamic Programming based
// solution to compute nCr % p
// Returns nCr % p
function nCrModp($n, $r, $p)
{
// Optimization for the cases when r is large
if ($r > $n - $r)
$r = $n - $r;
// The array C is going
// to store last row of
// pascal triangle at
// the end. And last entry
// of last row is nCr
$C = array();
for( $i = 0; $i < $r + 1; $i++)
$C[$i] = 0;
// Top row of Pascal
// Triangle
$C[0] = 1;
// One by constructs remaining
// rows of Pascal Triangle from
// top to bottom
for ($i = 1; $i <= $n; $i++)
{
// Fill entries of current
// row using previous row values
for ($j = Min($i, $r); $j > 0; $j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
$C[$j] = ($C[$j] +
$C[$j - 1]) % $p;
}
return $C[$r];
}
// Driver Code
$n = 10; $r = 2;$p = 13;
echo "Value of nCr % p is ",
nCrModp($n, $r, $p);
// This code is contributed
// by anuj_67.
?>
JavaScript
<script>
// A Dynamic Programming based
// solution to compute nCr % p
// Returns nCr % p
function nCrModp(n,r,p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
let C = new Array(r + 1);
for(let i = 0; i < r + 1; i++)
C[i] = 0;
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (let i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (let j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// Driver program
let n = 10, r = 2, p = 13;
document.write("Value of nCr % p is "
+ nCrModp(n, r, p));
// This code is contributed by avanitrachhadiya2155
</script>
OutputValue of nCr % p is 6
Time complexity of above solution is O(n*r) and it requires O(r) space. There are more and better solutions to above problem.
Compute nCr % p | Set 2 (Lucas Theorem)
METHOD 2(Using Pascal Triangle and Dynamic Pro)
Another approach lies in utilizing the concept of the Pascal Triangle. Instead of calculating the nCr value for every n starting from n=0 till n=n, the approach aims at using the nth row itself for the calculation. The method proceeds by finding out a general relationship between nCr and nCr-1.
FORMULA: C(n,r)=C(n,r-1)* (n-r+1)/r
Example:
For instance, take n=5 and r=3.
Input: n = 5, r = 3, p = 1000000007
Output: 6
Explanation: 5C3 is 10 and 10 % 100000007 is 10.
As per the formula,
C(5,3)=5!/(3!)*(2!)
C(5,3)=10
Also,
C(5,2)=5!/(2!)*(3!)
C(5,2)=10
Let's try applying the above formula.
C(n,r)=C(n,r-1)* (n-r+1)/r
C(5,3)=C(5,2)*(5-3+1)/3
C(5,3)=C(5,2)*1
C(5,3)=10*1
The above example shows that C(n,r) can be easily calculated by calculating C(n,r-1) and multiplying the result with the term (n-r+1)/r. But this multiplication may cause integer overflow for large values of n. To tackle this situation, use modulo multiplication, and modulo division concepts in order to achieve optimizations in terms of integer overflow.
Let's find out how to build Pascal Triangle for the same.
{1}\\ {1\hspace{0.1cm} 1}\\ {1\hspace{0.1cm} 2\hspace{0.1cm} 1}\\ {1\hspace{0.1cm} 3\hspace{0.1cm} 3\hspace{0.1cm} 1}\\ {1 \hspace{0.1cm}4\hspace{0.1cm} 6\hspace{0.1cm} 4\hspace{0.1cm} 1}\\ {1\hspace{0.1cm} 5\hspace{0.1cm} 10\hspace{0.1cm} 10\hspace{0.1cm} 5\hspace{0.1cm} 1}
1D array declaration can be further optimized by just the declaration of a single variable to perform calculations. However, integer overflow demands other functions too for the final implementation.
The post below mentions the space and time-optimized implementation for the binary coefficient calculation.
C++
// C++ program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
#include <bits/stdc++.h>
using namespace std;
// Returns (a * b) % mod
long long moduloMultiplication(long long a, long long b,
long long mod)
{
// Initialize result
long long res = 0;
// Update a if it is more than
// or equal to mod
a %= mod;
while (b) {
// If b is odd, add a with result
if (b & 1)
res = (res + a) % mod;
// Here we assume that doing 2*a
// doesn't cause overflow
a = (2 * a) % mod;
b >>= 1; // b = b / 2
}
return res;
}
// C++ function for extended Euclidean Algorithm
long long int gcdExtended(long long int a, long long int b,
long long int* x,
long long int* y);
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't exists
long long int modInverse(long long int b, long long int m)
{
long long int x, y; // used in extended GCD algorithm
long long int g = gcdExtended(b, m, &x, &y);
// Return -1 if b and m are not co-prime
if (g != 1)
return -1;
// m is added to handle negative x
return (x % m + m) % m;
}
// C++ function for extended Euclidean Algorithm (used to
// find modular inverse.
long long int gcdExtended(long long int a, long long int b,
long long int* x,
long long int* y)
{
// Base Case
if (a == 0) {
*x = 0, *y = 1;
return b;
}
// To store results of recursive call
long long int x1, y1;
long long int gcd = gcdExtended(b % a, a, &x1, &y1);
// Update x and y using results of recursive
// call
*x = y1 - (b / a) * x1;
*y = x1;
return gcd;
}
// Function to compute a/b under modulo m
long long int modDivide(long long int a, long long int b,
long long int m)
{
a = a % m;
long long int inv = modInverse(b, m);
if (inv == -1)
// cout << "Division not defined";
return 0;
else
return (inv * a) % m;
}
// Function to calculate nCr % p
int nCr(int n, int r, int p)
{
// Edge Case which is not possible
if (r > n)
return 0;
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// x stores the current result at
long long int x = 1;
// each iteration
// Initialized to 1 as nC0 is always 1.
for (int i = 1; i <= r; i++) {
// Formula derived for calculating result is
// C(n,r-1)*(n-r+1)/r
// Function calculates x*(n-i+1) % p.
x = moduloMultiplication(x, (n + 1 - i), p);
// Function calculates x/i % p.
x = modDivide(x, i, p);
}
return x;
}
// Driver Code
int main()
{
long long int n = 5, r = 3, p = 1000000007;
cout << "Value of nCr % p is " << nCr(n, r, p);
return 0;
}
Java
// Java program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
import java.util.*;
class GFG
{
// Returns (a * b) % mod
static long moduloMultiplication(long a, long b,
long mod)
{
// Initialize result
long res = 0;
// Update a if it is more than
// or equal to mod
a %= mod;
while (b > 0) {
// If b is odd, add a with result
if ((b & 1) != 0)
res = (res + a) % mod;
// Here we assume that doing 2*a
// doesn't cause overflow
a = (2 * a) % mod;
b >>= 1; // b = b / 2
}
return res;
}
// Global Variables
static long x, y;
// Function for extended Euclidean Algorithm
static long gcdExtended(long a, long b)
{
// Base Case
if (a == 0) {
x = 0;
y = 1;
return b;
}
// To store results of recursive call
long gcd = gcdExtended(b % a, a);
long x1 = x;
long y1 = y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
static long modInverse(long a, long m)
{
long g = gcdExtended(a, m);
// Return -1 if b and m are not co-prime
if (g != 1)
return -1;
// m is added to handle negative x
return (x % m + m) % m;
}
// Function to compute a/b under modulo m
static long modDivide(long a, long b, long m)
{
a = a % m;
long inv = modInverse(b, m);
if (inv == -1)
return 0;
else
return (inv * a) % m;
}
// Function to calculate nCr % p
static long nCr(long n, long r, long p)
{
// Edge Case which is not possible
if (r > n)
return 0;
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// x stores the current result at
long x = 1;
// each iteration
// Initialized to 1 as nC0 is always 1.
for (long i = 1L; i <= r; i++) {
// Formula derived for calculating result is
// C(n,r-1)*(n-r+1)/r
// Function calculates x*(n-i+1) % p.
x = moduloMultiplication(x, (n + 1L - i), p);
// Function calculates x/i % p.
x = modDivide(x, i, p);
}
return x;
}
// Driver Code
public static void main(String[] args)
{
long n = 5, r = 3, p = 1000000007;
System.out.println("Value of nCr % p is "
+ nCr(n, r, p));
}
}
// This code is contributed by phasing17
Python3
# Python3 program to find the nCr%p
# based on optimal Dynamic
# Programming implementation and
# Pascal Triangle concepts
# Returns (a * b) % mod
def moduloMultiplication(a, b, mod):
# Initialize result
res = 0
# Update a if it is more than
# or equal to mod
a %= mod
while (b):
# If b is odd, add a with result
if (b & 1):
res = (res + a) % mod
# Here we assume that doing 2*a
# doesn't cause overflow
a = (2 * a) % mod
b >>= 1 # b = b / 2
return res
# Global Variables
x, y = 0, 1
# Function for extended Euclidean Algorithm
def gcdExtended(a, b):
global x, y
# Base Case
if (a == 0):
x = 0
y = 1
return b
# To store results of recursive call
gcd = gcdExtended(b % a, a)
x1 = x
y1 = y
# Update x and y using results of recursive
# call
x = y1 - int(b / a) * x1
y = x1
return gcd
def modInverse(a, m):
g = gcdExtended(a, m)
# Return -1 if b and m are not co-prime
if (g != 1):
return -1
# m is added to handle negative x
return (x % m + m) % m
# Function to compute a/b under modulo m
def modDivide(a, b, m):
a = a % m
inv = modInverse(b, m)
if (inv == -1):
return 0
else:
return (inv * a) % m
# Function to calculate nCr % p
def nCr(n, r, p):
# Edge Case which is not possible
if (r > n):
return 0
# Optimization for the cases when r is large
if (r > n - r):
r = n - r
# x stores the current result at
x = 1
# each iteration
# Initialized to 1 as nC0 is always 1.
for i in range(1, r + 1):
# Formula derived for calculating result is
# C(n,r-1)*(n-r+1)/r
# Function calculates x*(n-i+1) % p.
x = moduloMultiplication(x, (n + 1 - i), p)
# Function calculates x/i % p.
x = modDivide(x, i, p)
return x
# Driver Code
n = 5
r = 3
p = 1000000007
print("Value of nCr % p is ", nCr(n, r, p))
# This code is contributed by phasing17
C#
// C# program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
using System;
using System.Collections.Generic;
class GFG
{
// Returns (a * b) % mod
static long moduloMultiplication(long a, long b, long mod)
{
// Initialize result
long res = 0;
// Update a if it is more than
// or equal to mod
a %= mod;
while (b > 0) {
// If b is odd, add a with result
if ((b & 1) != 0)
res = (res + a) % mod;
// Here we assume that doing 2*a
// doesn't cause overflow
a = (2 * a) % mod;
b >>= 1; // b = b / 2
}
return res;
}
// Global Variables
static long x, y;
// Function for extended Euclidean Algorithm
static long gcdExtended(long a, long b){
// Base Case
if (a == 0)
{
x = 0;
y = 1;
return b;
}
// To store results of recursive call
long gcd = gcdExtended(b % a, a);
long x1 = x;
long y1 = y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
static long modInverse(long a, long m)
{
long g = gcdExtended(a, m);
// Return -1 if b and m are not co-prime
if (g != 1)
return -1;
// m is added to handle negative x
return (x % m + m) % m;
}
// Function to compute a/b under modulo m
static long modDivide(long a, long b, long m)
{
a = a % m;
long inv = modInverse(b, m);
if (inv == -1)
return 0;
else
return (inv * a) % m;
}
// Function to calculate nCr % p
static long nCr(long n, long r, long p)
{
// Edge Case which is not possible
if (r > n)
return 0;
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// x stores the current result at
long x = 1;
// each iteration
// Initialized to 1 as nC0 is always 1.
for (long i = 1L; i <= r; i++) {
// Formula derived for calculating result is
// C(n,r-1)*(n-r+1)/r
// Function calculates x*(n-i+1) % p.
x = moduloMultiplication(x, (n + 1L - i), p);
// Function calculates x/i % p.
x = modDivide(x, i, p);
}
return x;
}
// Driver Code
public static void Main(string[] args)
{
long n = 5, r = 3, p = 1000000007;
Console.Write("Value of nCr % p is " + nCr(n, r, p));
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
// Returns (a * b) % mod
function moduloMultiplication(a, b, mod)
{
// Initialize result
let res = 0;
// Update a if it is more than
// or equal to mod
a %= mod;
while (b) {
// If b is odd, add a with result
if (b & 1)
res = (res + a) % mod;
// Here we assume that doing 2*a
// doesn't cause overflow
a = (2 * a) % mod;
b >>= 1; // b = b / 2
}
return res;
}
// Global Variables
let x, y;
// Function for extended Euclidean Algorithm
function gcdExtended(a, b){
// Base Case
if (a == 0)
{
x = 0;
y = 1;
return b;
}
// To store results of recursive call
let gcd = gcdExtended(b % a, a);
let x1 = x;
let y1 = y;
// Update x and y using results of recursive
// call
x = y1 - Math.floor(b / a) * x1;
y = x1;
return gcd;
}
function modInverse(a, m)
{
let g = gcdExtended(a, m);
// Return -1 if b and m are not co-prime
if (g != 1)
return -1;
// m is added to handle negative x
return (x % m + m) % m;
}
// Function to compute a/b under modulo m
function modDivide(a, b, m)
{
a = a % m;
let inv = modInverse(b, m);
if (inv == -1)
return 0;
else
return (inv * a) % m;
}
// Function to calculate nCr % p
function nCr(n, r, p)
{
// Edge Case which is not possible
if (r > n)
return 0;
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// x stores the current result at
let x = 1;
// each iteration
// Initialized to 1 as nC0 is always 1.
for (var i = 1; i <= r; i++) {
// Formula derived for calculating result is
// C(n,r-1)*(n-r+1)/r
// Function calculates x*(n-i+1) % p.
x = moduloMultiplication(x, (n + 1 - i), p);
// Function calculates x/i % p.
x = modDivide(x, i, p);
}
return x;
}
// Driver Code
let n = 5, r = 3, p = 1000000007;
console.log("Value of nCr % p is ", nCr(n, r, p));
// This code is contributed by phasing17
OutputValue of nCr % p is 10
Complexity Analysis:
- The above code needs an extra of O(1) space for the calculations.
- The time involved in the calculation of nCr % p is of the order O(n).
This article is improved by Aryan Gupta.
Similar Reads
Mathematical Algorithms
The following is the list of mathematical coding problem ordered topic wise. Please refer Mathematical Algorithms (Difficulty Wise) for the difficulty wise list of problems. GCD and LCM: GCD of Two Numbers LCM of Two Numbers LCM of array GCD of array Basic and Extended Euclidean Steinâs Algorithm fo
5 min read
Divisibility & Large Numbers
Check if a large number is divisible by 3 or not
Given a number, the task is that we divide number by 3. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input : n = 769452Output : YesInput : n = 123456758933312Output : NoInput : n = 3635883959606670431112222Output : YesSince input number may
7 min read
Check if a large number is divisible by 4 or not
Given a number, the task is to check if a number is divisible by 4 or not. The input number may be large and it may not be possible to store even if we use long long int.Examples:Input : n = 1124Output : YesInput : n = 1234567589333862Output : NoInput : n = 363588395960667043875487Output : NoUsing t
12 min read
Check if a large number is divisible by 6 or not
Given a number, the task is to check if a number is divisible by 6 or not. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input : n = 2112Output: YesInput : n = 1124Output : NoInput : n = 363588395960667043875487Output : NoC++#include <ios
7 min read
Check divisibility by 7
Given a number n, the task is to check if it is divisible by 7 or not.Note: You are not allowed to use the modulo operator, floating point arithmetic is also not allowed. Examples:Input: n = 371Output: TrueExplanation: The number 371: 37 - (2Ã1) = 37 - 2 = 35; 3 - (2 Ã 5) = 3 - 10 = -7; thus, since
6 min read
Check if a large number is divisible by 9 or not
Given a large number as a string s, determine if it is divisible by 9.Note: The number might be so large that it can't be stored in standard data types like long long.Examples: Input : s = "69354"Output: YesExplanation: 69354 is divisible by 9.Input: s = "234567876799333"Output: NoExplanation: 23456
3 min read
Check if a large number is divisible by 11 or not
Given a number, the task is to check if the number is divisible by 11 or not. The input number may be large and it may not be possible to store it even if we use long long int.Examples: Input : n = 76945Output : YesInput : n = 1234567589333892Output : YesInput : n = 363588395960667043875487Output :
7 min read
Divisibility by 12 for a large number
Given a large number, the task is to check whether the number is divisible by 12 or not. Examples : Input : 12244824607284961224 Output : Yes Input : 92387493287593874594898678979792 Output : No Method 1: This is a very simple approach. if a number is divisible by 4 and 3 then the number is divisibl
8 min read
Check if a large number is divisible by 13 or not
Given a large number, the task is to check if the number is divisible by 13 or not. Examples : Input : 637Output : 637 is divisible by 13.Input : 920Output : 920 is not divisible by 13.Input : 83959092724Output : 83959092724 is divisible by 13.[Naive Approach] - Modulo Division If the given number i
14 min read
Check if a large number is divisibility by 15
Given a very large number. Check its divisibility by 15. Examples: Input: "31"Output: NoInput : num = "156457463274623847239840239 402394085458848462385346236 482374823647643742374523747 264723762374620"Output: YesGiven number is divisible by 15A number is divisible by 15 if it is divisible by 5 (if
5 min read
Number is divisible by 29 or not
Given a large number n, find if the number is divisible by 29.Examples : Input : 363927598 Output : No Input : 292929002929 Output : Yes A quick solution to check if a number is divisible by 29 or not is to add 3 times of last digit to rest number and repeat this process until number comes 2 digit.
5 min read
GCD and LCM
LCM of given array elements
In this article, we will learn how to find the LCM of given array elements.Given an array of n numbers, find the LCM of it. Example:Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252Table of Content[Naive Approach] Iterative LCM Calculation - O(n * log(min(a
14 min read
GCD of more than two (or array) numbers
Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
11 min read
Euclidean algorithms (Basic and Extended)
The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors.Examples:input: a = 12, b = 20Output: 4Explanatio
9 min read
Stein's Algorithm for finding GCD
Stein's algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Steinâs algorithm replaces division with arithmetic shifts, comparisons, and subtraction.Examples: Input: a = 17, b = 34 Output : 17Input: a = 50, b = 49Output: 1Algorith
14 min read
GCD, LCM and Distributive Property
Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) where, GCD = Greatest Common Divisor, LCM = Least Common MultipleExamples: Input: x = 15, y = 20, z = 100Output: 60Explanation: The GCD of 15 and 20 is 5, and the LCM of 15 and 20 is 60, which is then multiplie
4 min read
Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
Given a number n, we need to find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2Output : 3The pairs are (1, 1) (2, 2) and (2, 1) Input : n = 3Output : 5(1, 1) (2, 2) (3, 3) (2, 1) and (3, 1)[Naive Approach] Counting GCD Pairs by Divisor Propertygcd(a, b) =
6 min read
Program to find GCD of floating point numbers
The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9Output : 0.3Explanation: The GCD of 0.3 and 0.9 is 0.3 because both numbers share 0.3 as the largest common divisor.Input : 0.48
4 min read
Series with largest GCD and sum equals to n
Given an integer n, print m increasing numbers such that the sum of m numbers is equal to n and the GCD of m numbers is maximum among all series possible. If no series is possible then print â-1â.Examples : Input : n = 24, m = 3 Output : 4 8 12 Explanation : (4, 8, 12) has gcd = 4 which is the maxim
11 min read
Largest Subset with GCD 1
Given n integers, we need to find size of the largest subset with GCD equal to 1. Input Constraint : n <= 10^5, A[i] <= 10^5Examples: Input : A = {2, 3, 5}Output : 3Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.Input
6 min read
Summation of GCD of all the pairs up to n
Given a number n, find sum of all GCDs that can be formed by selecting all the pairs from 1 to n. Examples: Input : n = 4Output : 7Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7Input : n = 12Output
10 min read
Series
Juggler Sequence
Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor & for \quad even \quad a
5 min read
Padovan Sequence
Padovan Sequence similar to Fibonacci sequence with similar recursive structure. The recursive formula is, P(n) = P(n-2) + P(n-3) P(0) = P(1) = P(2) = 1 Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...... Spiral of squares with side lengths which follow the Fibonacci sequence. Padovan Sequ
4 min read
Aliquot Sequence
Given a number n, the task is to print its Aliquot Sequence. Aliquot Sequence of a number starts with itself, remaining terms of the sequence are sum of proper divisors of immediate previous term. For example, Aliquot Sequence for 10 is 10, 8, 7, 1, 0. The sequence may repeat. For example, for 6, we
8 min read
Moser-de Bruijn Sequence
Given an integer 'n', print the first 'n' terms of the Moser-de Bruijn Sequence. Moser-de Bruijn sequence is the sequence obtained by adding up the distinct powers of the number 4 (For example, 1, 4, 16, 64, etc). Examples: Input : 5 Output : 0 1 4 5 16 Input : 10 Output : 0 1 4 5 16 17 20 21 64 65
12 min read
Stern-Brocot Sequence
Stern Brocot sequence is similar to Fibonacci sequence but it is different in the way fibonacci sequence is generated . Generation of Stern Brocot sequence : 1. First and second element of the sequence is 1 and 1.2. Consider the second member of the sequence . Then, sum the considered member of the
5 min read
Newman-Conway Sequence
Newman-Conway Sequence is the one that generates the following integer sequence. 1 1 2 2 3 4 4 4 5 6 7 7... In mathematical terms, the sequence P(n) of Newman-Conway numbers is defined by the recurrence relation P(n) = P(P(n - 1)) + P(n - P(n - 1)) with seed values P(1) = 1 and P(2) = 1 Given a numb
6 min read
Sylvester's sequence
In number system, Sylvester's sequence is an integer sequence in which each member of the sequence is the product of the previous members, plus one. Given a positive integer N. The task is to print the first N member of the sequence. Since numbers can be very big, use %10^9 + 7.Examples: Input : N =
4 min read
Recaman's sequence
Given an integer n. Print first n elements of Recamanâs sequence. Recaman's Sequence starts with 0 as the first term. For each next term, calculate previous term - index (if positive and not already in sequence); otherwise, use previous term + index.Examples: Input: n = 6Output: 0, 1, 3, 6, 2, 7Expl
8 min read
Sum of the sequence 2, 22, 222, .........
Given an integer n. The task is to find the sum of the following sequence: 2, 22, 222, ......... to n terms. Examples : Input: n = 2Output: 24Explanation: For n = 2, the sum of first 2 terms are 2 + 22 = 24Input: 3Output: 246Explanation: For n = 3, the sum of first 3 terms are 2 + 22 + 222 = 246Usin
8 min read
Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2
Given a series 12 + 32 + 52 + 72 + . . . + (2*n - 1)2, find the sum of the series.Examples: Input: n = 4Output: 84Explanation: sum = 12 + 32 + 52 + 72 = 1 + 9 + 25 + 49 = 84Input: n = 10 Output: 1330Explanation: sum = 12 + 32 + 52 + 72 + 92 + 112 + 132 + 152 + 172 + 192 = 1 + 9 + 24 + 49 + . . . + 3
3 min read
Sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms
Given the number of terms i.e. n. Find the sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms.Examples: Input: 2Output: 0.66Explanation: sum of the series upto 2 terms: 0.6 + 0.06 = 0.66.Input: 3Output: 0.666Explanation: sum of the series upto 3 terms: 0.6 + 0.06 + 0.006 = 0.666.Table of Cont
7 min read
n-th term in series 2, 12, 36, 80, 150....
Given a series 2, 12, 36, 80, 150.. Find the n-th term of the series.Examples : Input : 2 Output : 12 Input : 4 Output : 80 If we take a closer look, we can notice that series is sum of squares and cubes of natural numbers (1, 4, 9, 16, 25, .....) + (1, 8, 27, 64, 125, ....).Therefore n-th number of
3 min read
Number Digits
Minimum digits to remove to make a number Perfect Square
Given an integer n, we need to find how many digits remove from the number to make it a perfect square. Examples : Input : 8314 Output: 81 2 Explanation: If we remove 3 and 4 number becomes 81 which is a perfect square. Input : 57 Output : -1 The idea is to generate all possible subsequences and ret
9 min read
Print first k digits of 1/n where n is a positive integer
Given a positive integer n, print first k digits after point in value of 1/n. Your program should avoid overflow and floating point arithmetic.Examples : Input: n = 3, k = 3 Output: 333 Input: n = 50, k = 4 Output: 0200 We strongly recommend to minimize the browser and try this yourself first.Let us
5 min read
Check if a given number can be represented in given a no. of digits in any base
Given a number and no. of digits to represent the number, find if the given number can be represented in given no. of digits in any base from 2 to 32.Examples : Input: 8 4 Output: Yes Possible in base 2 as 8 in base 2 is 1000 Input: 8 2 Output: Yes Possible in base 3 as 8 in base 3 is 22 Input: 8 3
12 min read
Minimum Segments in Seven Segment Display
A seven-segment display can be used to display numbers. Given an array of n natural numbers. The task is to find the number in the array that uses the minimum number of segments to display the number. If multiple numbers have a minimum number of segments, output the number having the smallest index.
6 min read
Find next greater number with same set of digits
Given a number N as string, find the smallest number that has same set of digits as N and is greater than N. If N is the greatest possible number with its set of digits, then print "Not Possible".Examples: Input: N = "218765"Output: "251678"Explanation: The next number greater than 218765 with same
9 min read
Check if a number is jumbled or not
Write a program to check if a given integer is jumbled or not. A number is said to be Jumbled if for every digit, its neighbours digit differs by max 1. Examples : Input : 6765Output : TrueAll neighbour digits differ by atmost 1. Input : 1223Output : True Input : 1235Output : False Approach: Find th
6 min read
Numbers having difference with digit sum more than s
You are given two positive integer value n and s. You have to find the total number of such integer from 1 to n such that the difference of integer and its digit sum is greater than given s.Examples : Input : n = 20, s = 5 Output :11 Explanation : Integer from 1 to 9 have diff(integer - digitSum) =
7 min read
Total numbers with no repeated digits in a range
Given a range L, R find total such numbers in the given range such that they have no repeated digits. For example: 12 has no repeated digit. 22 has repeated digit. 102, 194 and 213 have no repeated digit. 212, 171 and 4004 have repeated digits. Examples: Input : 10 12 Output : 2 Explanation : In the
15+ min read
K-th digit in 'a' raised to power 'b'
Given three numbers a, b and k, find k-th digit in ab from right sideExamples: Input : a = 3, b = 3, k = 1Output : 7Explanation: 3^3 = 27 for k = 1. First digit is 7 in 27Input : a = 5, b = 2, k = 2Output : 2Explanation: 5^2 = 25 for k = 2. First digit is 2 in 25The approach is simple. Computes the
5 min read
Algebra
Program to add two polynomials
Given two polynomials represented by two arrays, write a function that adds given two polynomials. Example: Input: A[] = {5, 0, 10, 6} B[] = {1, 2, 4} Output: sum[] = {6, 2, 14, 6} The first input array represents "5 + 0x^1 + 10x^2 + 6x^3" The second array represents "1 + 2x^1 + 4x^2" And Output is
15+ min read
Multiply two polynomials
Given two polynomials represented by two arrays, write a function that multiplies the given two polynomials. In this representation, each index of the array corresponds to the exponent of the variable(e.g. x), and the value at that index represents the coefficient of the term. For example, the array
15+ min read
Find number of solutions of a linear equation of n variables
Given a linear equation of n variables, find number of non-negative integer solutions of it. For example, let the given equation be "x + 2y = 5", solutions of this equation are "x = 1, y = 2", "x = 5, y = 0" and "x = 3, y = 1". It may be assumed that all coefficients in given equation are positive i
10 min read
Calculate the Discriminant Value
In algebra, Discriminant helps us deduce various properties of the roots of a polynomial or polynomial function without even computing them. Let's look at this general quadratic polynomial of degree two: ax^2+bx+c Here the discriminant of the equation is calculated using the formula: b^2-4ac Now we
5 min read
Program for dot product and cross product of two vectors
There are two vector A and B and we have to find the dot product and cross product of two vector array. Dot product is also known as scalar product and cross product also known as vector product.Dot Product - Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k.
8 min read
Iterated Logarithm log*(n)
Iterated Logarithm or Log*(n) is the number of times the logarithm function must be iteratively applied before the result is less than or equal to 1. \log ^{*}n:=\begin{cases}0n\leq 1;\\1+\log ^{*}(\log n)n>1\end{cases} Applications: It is used in the analysis of algorithms (Refer Wiki for detail
4 min read
Program to Find Correlation Coefficient
The correlation coefficient is a statistical measure that helps determine the strength and direction of the relationship between two variables. It quantifies how changes in one variable correspond to changes in another. This coefficient, sometimes referred to as the cross-correlation coefficient, al
8 min read
Program for Muller Method
Given a function f(x) on floating number x and three initial distinct guesses for root of the function, find the root of function. Here, f(x) can be an algebraic or transcendental function.Examples: Input : A function f(x) = x^3 + 2x^2 + 10x - 20 and three initial guesses - 0, 1 and 2 .Output : The
13 min read
Number of non-negative integral solutions of a + b + c = n
Given a number n, find the number of ways in which we can add 3 non-negative integers so that their sum is n.Examples : Input : n = 1 Output : 3 There are three ways to get sum 1. (1, 0, 0), (0, 1, 0) and (0, 0, 1) Input : n = 2 Output : 6 There are six ways to get sum 2. (2, 0, 0), (0, 2, 0), (0, 0
7 min read
Generate Pythagorean Triplets
Given a positive integer limit, your task is to find all possible Pythagorean Triplet (a, b, c), such that a <= b <= c <= limit.Note: A Pythagorean triplet is a set of three positive integers a, b, and c such that a2 + b2 = c2. Input: limit = 20Output: 3 4 5 5 12 13 6 8 10 8 15 17 9 12 15 1
14 min read
Number System
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
5 min read
Check if a number is power of k using base changing method
This program checks whether a number n can be expressed as power of k and if yes, then to what power should k be raised to make it n. Following example will clarify : Examples: Input : n = 16, k = 2 Output : yes : 4 Explanation : Answer is yes because 16 can be expressed as power of 2. Input : n = 2
8 min read
Program to convert a binary number to hexadecimal number
Given a Binary Number, the task is to convert the given binary number to its equivalent hexadecimal number. The input could be very large and may not fit even into an unsigned long long int.Examples:Â Input: 110001110Output: 18EInput: 1111001010010100001.010110110011011Output: 794A1.5B36 794A1D9B App
13 min read
Program for decimal to hexadecimal conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16.Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and
8 min read
Converting a Real Number (between 0 and 1) to Binary String
Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print" ERROR:' Examples: Input : (0.625)10 Output : (0.101)2 Input : (0.72)10 Output : ERROR Solution:
12 min read
Convert from any base to decimal and vice versa
Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal. Examples: Input number is given as string a
15+ min read
Decimal to binary conversion without using arithmetic operators
Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = ""
8 min read
Prime Numbers & Primality Tests
Prime Numbers | Meaning | List 1 to 100 | Examples
Prime numbers are those natural numbers that are divisible by only 1 and the number itself. Numbers that have more than two divisors are called composite numbers All primes are odd, except for 2.Here, we will discuss prime numbers, the list of prime numbers from 1 to 100, various methods to find pri
12 min read
Left-Truncatable Prime
A Left-truncatable prime is a prime which in a given base (say 10) does not contain 0 and which remains prime when the leading ("left") digit is successively removed. For example, 317 is left-truncatable prime since 317, 17 and 7 are all prime. There are total 4260 left-truncatable primes.The task i
13 min read
Program to Find All Mersenne Primes till N
Mersenne Prime is a prime number that is one less than a power of two. In other words, any prime is Mersenne Prime if it is of the form 2k-1 where k is an integer greater than or equal to 2. First few Mersenne Primes are 3, 7, 31 and 127.The task is print all Mersenne Primes smaller than an input po
9 min read
Super Prime
Given a positive integer n and the task is to print all the Super-Primes less than or equal to n. Super-prime numbers (also known as higher order primes) are the subsequence of prime number sequence that occupy prime-numbered positions within the sequence of all prime numbers. The first few super pr
6 min read
Hardy-Ramanujan Theorem
Hardy Ramanujam theorem states that the number of prime factors of n will approximately be log(log(n)) for most natural numbers nExamples : 5192 has 2 distinct prime factors and log(log(5192)) = 2.1615 51242183 has 3 distinct prime facts and log(log(51242183)) = 2.8765 As the statement quotes, it is
6 min read
Rosser's Theorem
In mathematics, Rosser's Theorem states that the nth prime number is greater than the product of n and natural logarithm of n for all n greater than 1. Mathematically, For n >= 1, if pn is the nth prime number, then pn > n * (ln n) Illustrative Examples: For n = 1, nth prime number = 2 2 >
15 min read
Fermat's little theorem
Fermat's little theorem states that if p is a prime number, then for any integer a, the number a p - a is an integer multiple of p. Here p is a prime number ap â¡ a (mod p).Special Case: If a is not divisible by p, Fermat's little theorem is equivalent to the statement that a p-1-1 is an integer mult
8 min read
Introduction to Primality Test and School Method
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: trueInput: n = 15Output: falseInput: n = 1Output:
10 min read
Vantieghems Theorem for Primality Test
Vantieghems Theorem is a necessary and sufficient condition for a number to be prime. It states that for a natural number n to be prime, the product of 2^i - 1 where 0 < i < n , is congruent to n~(mod~(2^n - 1)) . In other words, a number n is prime if and only if.{\displaystyle \prod _{1\leq
4 min read
AKS Primality Test
There are several primality test available to check whether the number is prime or not like Fermat's Theorem, Miller-Rabin Primality test and alot more. But problem with all of them is that they all are probabilistic in nature. So, here comes one another method i.e AKS primality test (AgrawalâKayalâ
11 min read
Lucas Primality Test
A number p greater than one is prime if and only if the only divisors of p are 1 and p. First few prime numbers are 2, 3, 5, 7, 11, 13, ...The Lucas test is a primality test for a natural number n, it can test primality of any kind of number.It follows from Fermatâs Little Theorem: If p is prime and
12 min read
Prime Factorization & Divisors
Print all prime factors of a given number
Given a number n, the task is to find all prime factors of n.Examples:Input: n = 24Output: 2 2 2 3Explanation: The prime factorization of 24 is 23Ã3.Input: n = 13195Output: 5 7 13 29Explanation: The prime factorization of 13195 is 5Ã7Ã13Ã29.Approach:Every composite number has at least one prime fact
6 min read
Smith Number
Given a number n, the task is to find out whether this number is smith or not. A Smith Number is a composite number whose sum of digits is equal to the sum of digits in its prime factorization. Examples: Input : n = 4Output : YesPrime factorization = 2, 2 and 2 + 2 = 4Therefore, 4 is a smith numberI
15 min read
Sphenic Number
A Sphenic Number is a positive integer n which is a product of exactly three distinct primes. The first few sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114, ... Given a number n, determine whether it is a Sphenic Number or not. Examples: Input: 30Output : YesExplanation: 30 is the smalles
8 min read
Hoax Number
Given a number 'n', check whether it is a hoax number or not. A Hoax Number is defined as a composite number, whose sum of digits is equal to the sum of digits of its distinct prime factors. It may be noted here that, 1 is not considered a prime number, hence it is not included in the sum of digits
13 min read
k-th prime factor of a given number
Given two numbers n and k, print k-th prime factor among all prime factors of n. For example, if the input number is 15 and k is 2, then output should be "5". And if the k is 3, then output should be "-1" (there are less than k prime factors). Examples: Input : n = 225, k = 2 Output : 3 Prime factor
15+ min read
Pollard's Rho Algorithm for Prime Factorization
Given a positive integer n, and that it is composite, find a divisor of it.Example:Input: n = 12;Output: 2 [OR 3 OR 4]Input: n = 187;Output: 11 [OR 17]Brute approach: Test all integers less than n until a divisor is found. Improvisation: Test all integers less than ?nA large enough number will still
14 min read
Finding power of prime number p in n!
Given a number 'n' and a prime number 'p'. We need to find out the power of 'p' in the prime factorization of n!Examples: Input : n = 4, p = 2 Output : 3 Power of 2 in the prime factorization of 2 in 4! = 24 is 3 Input : n = 24, p = 2 Output : 22 Naive approach The naive approach is to find the powe
8 min read
Find all factors of a Natural Number
Given a natural number n, print all distinct divisors of it.Examples:Input: n = 10 Output: 1 2 5 10Explanation: 1, 2, 5 and 10 are the factors of 10. Input: n = 100Output: 1 2 4 5 10 20 25 50 100Explanation: 1, 2, 4, 5, 10, 20, 25, 50 and 100 are factors of 100.Input: n = 125Output: 1 5 25 125Note t
7 min read
Find numbers with n-divisors in a given range
Given three integers a, b, n .Your task is to print number of numbers between a and b including them also which have n-divisors. A number is called n-divisor if it has total n divisors including 1 and itself. Examples: Input : a = 1, b = 7, n = 2 Output : 4 There are four numbers with 2 divisors in
14 min read
Modular Arithmetic
Modular Exponentiation (Power in Modular Arithmetic)
Modular Exponentiation is the process of computing: xy (modââp). where x, y, and p are integers. It efficiently calculates the remainder when xy is divided by p or (xy) % p, even for very large y.Examples : Input: x = 2, y = 3, p = 5Output: 3Explanation: 2^3 % 5 = 8 % 5 = 3.Input: x = 2, y = 5, p =
8 min read
Modular multiplicative inverse
Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that:A X â¡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*0 m
15+ min read
Modular Division
Modular division is the process of dividing one number by another in modular arithmetic. In modular arithmetic, division is defined differently from regular arithmetic because there is no direct "division" operation. Instead, modular division involves multiplying by the modular multiplicative invers
10 min read
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
11 min read
Find sum of modulo K of first N natural number
Given two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
9 min read
How to compute mod of a big number?
Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer. Examples : Input: num = "12316767678678", a = 10 Output: num (mod a) ? 8 The idea is to process all digits one by one and use the property that xy (mod a) ? ((x
4 min read
Exponential Squaring (Fast Modulo Multiplication)
Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7 Examples: Input : base = 2, exp = 2Output : 4Input : base = 5, exp = 100000Output : 754573817In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the valu
12 min read
Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
Given integers x1, x2, x3......xn, b, and m, we are supposed to find the result of ((x1*x2....xn)/b)mod(m). Example 1: Suppose that we are required to find (55C5)%(1000000007) i.e ((55*54*53*52*51)/120)%1000000007 Naive Method : Simply calculate the product (55*54*53*52*51)= say x,Divide x by 120 a
9 min read