Bell Numbers (Number of ways to Partition a Set)
Last Updated : 09 Nov, 2024
Given a set of n elements, find the number of ways of partitioning it.
Examples:
Input: n = 2
Output: 2
Explanation: Let the set be {1, 2}. The partitions are {{1},{2}} and {{1, 2}}.
Input: n = 3
Output: 5
Explanation: Let the set be {1, 2, 3}. The partitions are {{1},{2},{3}}, {{1},{2, 3}}, {{2},{1, 3}}, {{3},{1, 2}}, {{1, 2, 3}}.
What is a Bell Number?
Let S(n, k) be total number of partitions of n elements into k sets. The value of the n'th Bell Number is the sum of S(n, k) for k = 1 to n.
Bell(n)=∑S (n,k) for k ranges from [1,n]
Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1)
How does above recursive formula work?
When we add a (n+1)'th element to k partitions, there are two possibilities.
1) It is added as a single element set to existing partitions, i.e, S(n, k-1)
2) It is added to all sets of every partition, i.e., k*S(n, k).
First few Bell numbers are 1, 1, 2, 5, 15, 52, 203, ....
Using recursion - O(2 ^ n) Time and O(n) Space
We can recursively calculate the number of ways to partition a set of n
elements by considering each element and either placing it in an existing subset or creating a new subset. For each element, we calculate the number of ways to partition the remaining n-1
elements into k
subsets and then sum these values for all possible k
. This gives us the following recurrence relation for Stirling numbers of the second kind:
- S(n,k) = k * S( n - 1, k) + S(n - 1, k - 1)
Finally, to find the Bell number, we sum S(n, k) for all values of k from 1 to n. This gives us the total number of ways to partition the set.
C++ // C++ code of finding the bellNumber // using recursion #include <iostream> #include <vector> using namespace std; // Function to compute Stirling numbers of // the second kind S(n, k) with memoization int stirling(int n, int k) { // Base cases if (n == 0 && k == 0) return 1; if (k == 0 || n == 0) return 0; if (n == k) return 1; if (k == 1) return 1; // Recursive formula return k * stirling(n - 1, k) + stirling(n - 1, k - 1); } // Function to calculate the total number of // ways to partition a set of `n` elements int bellNumber(int n) { int result = 0; // Sum up Stirling numbers S(n, k) for all // k from 1 to n for (int k = 1; k <= n; ++k) { result += stirling(n, k); } return result; } int main() { int n = 5; int result = bellNumber(n); cout << result << endl; return 0; }
Java // Java program to find the Bell Number // using recursion class GfG { // Function to compute Stirling numbers of // the second kind S(n, k) with memoization static int stirling(int n, int k) { // Base cases if (n == 0 && k == 0) return 1; if (k == 0 || n == 0) return 0; if (n == k) return 1; if (k == 1) return 1; // Recursive formula return k * stirling(n - 1, k) + stirling(n - 1, k - 1); } // Function to calculate the total number of // ways to partition a set of `n` elements static int bellNumber(int n) { int result = 0; // Sum up Stirling numbers S(n, k) for // all k from 1 to n for (int k = 1; k <= n; ++k) { result += stirling(n, k); } return result; } public static void main(String[] args) { int n = 5; int result = bellNumber(n); System.out.println(result); } }
Python # Python program to find the Bell Number using recursion # Function to compute Stirling numbers of # the second kind S(n, k) with memoization def stirling(n, k): # Base cases if n == 0 and k == 0: return 1 if k == 0 or n == 0: return 0 if n == k: return 1 if k == 1: return 1 # Recursive formula return k * stirling(n - 1, k) + stirling(n - 1, k - 1) # Function to calculate the total number of # ways to partition a set of `n` elements def bellNumber(n): result = 0 # Sum up Stirling numbers S(n, k) for # all k from 1 to n for k in range(1, n + 1): result += stirling(n, k) return result n = 5 result = bellNumber(n) print(result)
C# // C# program to find the Bell Number // using recursion using System; class GfG { // Function to compute Stirling numbers of // the second kind S(n, k) with memoization static int Stirling(int n, int k) { // Base cases if (n == 0 && k == 0) return 1; if (k == 0 || n == 0) return 0; if (n == k) return 1; if (k == 1) return 1; // Recursive formula return k * Stirling(n - 1, k) + Stirling(n - 1, k - 1); } // Function to calculate the total number of // ways to partition a set of `n` elements static int BellNumber(int n) { int result = 0; // Sum up Stirling numbers S(n, k) for all // k from 1 to n for (int k = 1; k <= n; ++k) { result += Stirling(n, k); } return result; } public static void Main(string[] args) { int n = 5; int result = BellNumber(n); Console.WriteLine(result); } }
JavaScript // JavaScript program to find the Bell Number using recursion // Function to compute Stirling numbers of // the second kind S(n, k) with memoization function stirling(n, k) { // Base cases if (n === 0 && k === 0) return 1; if (k === 0 || n === 0) return 0; if (n === k) return 1; if (k === 1) return 1; // Recursive formula return k * stirling(n - 1, k) + stirling(n - 1, k - 1); } // Function to calculate the total number of // ways to partition a set of `n` elements function bellNumber(n) { let result = 0; // Sum up Stirling numbers S(n, k) for all // k from 1 to n for (let k = 1; k <= n; ++k) { result += stirling(n, k); } return result; } let n = 5; let result = bellNumber(n); console.log(result);
Using Top-Down DP (Memoization) - O(n^2) Time and O(n^2) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: The number of ways to partition a set of n elements into k subsets depends on two smaller subproblems:
- The number of ways to partition the first n-1 elements into k subsets, and
- The number of ways to partition the first n-1 elements into k-1 subsets and then add the new element as its own subset. By combining these optimal solutions, we can efficiently calculate the total number of ways to partition the set.
2. Overlapping Subproblems: In the recursive approach, certain subproblems are recalculated multiple times. For example, when computing S(n, k), the subproblems S(n-1, k) and S(n-1, k-1) are recomputed multiple times. This redundancy leads to overlapping subproblems, which can be avoided using memoization or tabulation.
Follow the steps below to solve the problem:
- Use recursion with memoization to calculate Stirling numbers of the second kind, S(n,k), which represent the number of ways to partition n items into k non-empty subsets.
- Define base cases for S(0, 0), S(n, 0), S(n, n), and S(n, 1) to handle specific situations in the recursive formula.
- Use the formula S(n, k) = k × S(n-1, k) + S(n-1, k-1) to compute the Stirling numbers with previously stored results.
- For a given n, sum S(n, k) for all from 1 to n to calculate the Bell number, which represents the total ways to partition n elements.
- Output the computed Bell number for the given n.
C++ // C++ code of finding the bellNumber // using Memoization #include <iostream> #include <vector> using namespace std; // Function to compute Stirling numbers of // the second kind S(n, k) with memoization int stirling(int n, int k, vector<vector<int>>& memo) { // Base cases if (n == 0 && k == 0) return 1; if (k == 0 || n == 0) return 0; if (n == k) return 1; if (k == 1) return 1; // Check if result is already computed if (memo[n][k] != -1) return memo[n][k]; // Recursive formula memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo); return memo[n][k]; } // Function to calculate the total number of // ways to partition a set of `n` elements int bellNumber(int n) { // Initialize memoization table with -1 vector<vector<int>> memo(n + 1, vector<int>(n + 1, -1)); int result = 0; // Sum up Stirling numbers S(n, k) for all // k from 1 to n for (int k = 1; k <= n; ++k) { result += stirling(n, k, memo); } return result; } int main() { int n = 5; int result = bellNumber(n); cout << result << endl; return 0; }
Java // Java code of finding the bellNumber // using Memoization import java.util.Arrays; class GfG { // Function to compute Stirling numbers of // the second kind S(n, k) with memoization static int stirling(int n, int k, int[][] memo) { // Base cases if (n == 0 && k == 0) return 1; if (k == 0 || n == 0) return 0; if (n == k) return 1; if (k == 1) return 1; // Check if result is already computed if (memo[n][k] != -1) return memo[n][k]; // Recursive formula memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo); return memo[n][k]; } // Function to calculate the total number of // ways to partition a set of n elements static int bellNumber(int n) { // Initialize memoization table with -1 int[][] memo = new int[n + 1][n + 1]; for (int[] row : memo) Arrays.fill(row, -1); int result = 0; // Sum up Stirling numbers S(n, k) for all k from 1 to n for (int k = 1; k <= n; ++k) { result += stirling(n, k, memo); } return result; } public static void main(String[] args) { int n = 5; int result = bellNumber(n); System.out.println(result); } }
Python # Python code of finding the bellNumber # Using Memoization # Function to compute Stirling numbers of # the second kind S(n, k) with memoization def stirling(n, k, memo): # Base cases if n == 0 and k == 0: return 1 if k == 0 or n == 0: return 0 if n == k: return 1 if k == 1: return 1 # Check if result is already # computed if memo[n][k] != -1: return memo[n][k] # Recursive formula memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo) return memo[n][k] # Function to calculate the total number of # ways to partition a set of n elements def bellNumber(n): # Initialize memoization table with -1 memo = [[-1 for _ in range(n + 1)] for _ in range(n + 1)] result = 0 # Sum up Stirling numbers S(n, k) for all k from 1 to n for k in range(1, n + 1): result += stirling(n, k, memo) return result if __name__ == "__main__": n = 5 result = bellNumber(n) print(result)
C# //C# code of finding the bellNumber // using Memoization using System; class GfG { // Function to compute Stirling numbers of // the second kind S(n, k) with memoization static int Stirling(int n, int k, int[, ] memo) { // Base cases if (n == 0 && k == 0) return 1; if (k == 0 || n == 0) return 0; if (n == k) return 1; if (k == 1) return 1; // Check if result is already // computed if (memo[n, k] != -1) return memo[n, k]; // Recursive formula memo[n, k] = k * Stirling(n - 1, k, memo) + Stirling(n - 1, k - 1, memo); return memo[n, k]; } // Function to calculate the total number of // ways to partition a set of n elements static int BellNumber(int n) { // Initialize memoization table with -1 int[, ] memo = new int[n + 1, n + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) memo[i, j] = -1; int result = 0; // Sum up Stirling numbers S(n, k) for all k from 1 // to n for (int k = 1; k <= n; ++k) { result += Stirling(n, k, memo); } return result; } static void Main(string[] args) { int n = 5; int result = BellNumber(n); Console.WriteLine(result); } }
JavaScript // JavaScript code of finding the bellNumber // using Memoization // Function to compute Stirling numbers of // the second kind S(n, k) with memoization function stirling(n, k, memo) { // Base cases if (n === 0 && k === 0) return 1; if (k === 0 || n === 0) return 0; if (n === k) return 1; if (k === 1) return 1; // Check if result is already computed if (memo[n][k] !== -1) return memo[n][k]; // Recursive formula memo[n][k] = k * stirling(n - 1, k, memo) + stirling(n - 1, k - 1, memo); return memo[n][k]; } // Function to calculate the total number of // ways to partition a set of n elements function bellNumber(n) { // Initialize memoization table with -1 let memo = Array.from({ length: n + 1 }, () => Array(n + 1).fill(-1)); let result = 0; // Sum up Stirling numbers S(n, k) for all k from 1 to n for (let k = 1; k <= n; ++k) { result += stirling(n, k, memo); } return result; } let n = 5; let result = bellNumber(n); console.log(result);
Using Bottom-Up DP (Tabulation - 1) - O(n^2) Time and O(n^2) Space
A Simple Method to compute n'th Bell Number is to one by one compute S(n, k) for k = 1 to n and return sum of all computed values. Refer Count number of ways to partition a set into k subsets for computation of S(n, k).
C++ // C++ code to calculate the Bell number for a given // integer `n` #include <iostream> #include <vector> using namespace std; // Function to calculate the Bell number for a given integer `n` int bellNumber(int n) { // Create a 2D vector for Stirling numbers of // the second kind vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0)); // Fill the table using dynamic programming for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { // These are some base cases if (j > i) dp[i][j] = 0; else if (i == j) dp[i][j] = 1; else if (i == 0 || j == 0) dp[i][j] = 0; else { // Recurrence relation: Stirling number calculation dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; } } } // Sum up Stirling numbers for all j // from 0 to n to get the Bell number int ans = 0; for (int i = 0; i <= n; i++) { ans += dp[n][i]; } // Return the Bell number return ans; } int main() { int n = 5; int result = bellNumber(n); cout << result << endl; return 0; }
Java // Java code to calculate the Bell number for a given // integer `n` class GfG { // Function to calculate the Bell number for a given // integer `n` static int bellNumber(int n) { // Create a 2D vector for Stirling numbers of the // second kind int[][] dp = new int[n + 1][n + 1]; // Fill the table using dynamic programming for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { // These are some base cases if (j > i) dp[i][j] = 0; else if (i == j) dp[i][j] = 1; else if (i == 0 || j == 0) dp[i][j] = 0; else { // Recurrence relation: Stirling number // calculation dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; } } } // Sum up Stirling numbers for all j // from 0 to n to get the Bell number int ans = 0; for (int i = 0; i <= n; i++) { ans += dp[n][i]; } // Return the Bell number return ans; } public static void main(String[] args) { int n = 5; int result = bellNumber(n); System.out.println(result); } }
Python # Python code to calculate the Bell number for a given integer `n` # Function to calculate the Bell number for a # given integer `n` def bellNumber(n): # Create a 2D list for Stirling numbers of # the second kind dp = [[0] * (n + 1) for _ in range(n + 1)] # Fill the table using dynamic programming for i in range(n + 1): for j in range(n + 1): # These are some base cases if j > i: dp[i][j] = 0 elif i == j: dp[i][j] = 1 elif i == 0 or j == 0: dp[i][j] = 0 else: # Recurrence relation: Stirling number calculation dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1] # Sum up Stirling numbers for all j # from 0 to n to get the Bell number ans = 0 for i in range(n + 1): ans += dp[n][i] # Return the Bell number return ans if __name__ == "__main__": n = 5 result = bellNumber(n) print(result)
C# // C# code to calculate the Bell number for a given integer // `n` using System; class GfG { // Function to calculate the Bell number for a given // integer `n` static int BellNumber(int n) { // Create a 2D array for Stirling numbers of the // second kind int[, ] dp = new int[n + 1, n + 1]; // Fill the table using dynamic programming for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { // These are some base cases if (j > i) dp[i, j] = 0; else if (i == j) dp[i, j] = 1; else if (i == 0 || j == 0) dp[i, j] = 0; else { // Recurrence relation: Stirling number // calculation dp[i, j] = j * dp[i - 1, j] + dp[i - 1, j - 1]; } } } // Sum up Stirling numbers for all j // from 0 to n to get the Bell number int ans = 0; for (int i = 0; i <= n; i++) { ans += dp[n, i]; } // Return the Bell number return ans; } static void Main(string[] args) { int n = 5; int result = BellNumber(n); Console.WriteLine(result); } }
Javascript // JavaScript code to calculate the Bell number for a given // integer `n` // Function to calculate the Bell number for a given integer // `n` function bellNumber(n) { // Create a 2D array for Stirling numbers of the second // kind let dp = Array.from({length : n + 1}, () => Array(n + 1).fill(0)); // Fill the table using dynamic programming for (let i = 0; i <= n; i++) { for (let j = 0; j <= n; j++) { // These are some base cases if (j > i) dp[i][j] = 0; else if (i === j) dp[i][j] = 1; else if (i === 0 || j === 0) dp[i][j] = 0; else { // Recurrence relation: Stirling number // calculation dp[i][j] = j * dp[i - 1][j] + dp[i - 1][j - 1]; } } } // Sum up Stirling numbers for all j // from 0 to n to get the Bell number let ans = 0; for (let i = 0; i <= n; i++) { ans += dp[n][i]; } // Return the Bell number return ans; } let n = 5; let result = bellNumber(n); console.log(result);
Using Bottom-Up DP (Tabulation - 2) - O(n^2) Time and O(n^2) Space
A Better Method is to use Bell Triangle. Below is a sample Bell Triangle for first few Bell Numbers.
1
1 2
2 3 5
5 7 10 15
15 20 27 37 52
Follow the steps below to solve the problem:
- Create a 2D array to store Bell numbers, starting with bell[0][0] = 1 as the base case.
- Use dynamic programming to fill the table based on the recurrence relation. For each i, set bell[i][0] = bell[i-1][i-1] and compute bell[i][j] using the formula bell[i][j] = bell[i-1][j-1] + bell[i][j-1] for all valid j.
- The formula computes the Bell numbers by using the Stirling numbers of the second kind, which count ways to partition a set of i elements into j non-empty subsets.
- The Bell number for n is stored in bell[n][0].
C++14 // A C++ program to find n'th Bell number #include <iostream> using namespace std; int bellNumber(int n) { int dp[n + 1][n + 1]; dp[0][0] = 1; for (int i = 1; i <= n; i++) { // Explicitly fill for j = 0 dp[i][0] = dp[i - 1][i - 1]; // Fill for remaining values of j for (int j = 1; j <= i; j++) dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]; } return dp[n][0]; } int main() { int n = 5; int result = bellNumber(n); cout << result << endl; return 0; }
Java // Java program to find n'th Bell number class GfG { // Function to calculate the Bell number for a given // integer `n` static int bellNumber(int n) { int[][] dp = new int[n + 1][n + 1]; dp[0][0] = 1; for (int i = 1; i <= n; i++) { // Explicitly fill for j = 0 dp[i][0] = dp[i - 1][i - 1]; // Fill for remaining values of j for (int j = 1; j <= i; j++) dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]; } return dp[n][0]; } public static void main(String[] args) { int n = 5; int result = bellNumber(n); System.out.println(result); } }
Python # Python program to find n'th Bell number # Function to calculate the Bell number for a given integer `n` def bellNumber(n): dp = [[0] * (n + 1) for _ in range(n + 1)] dp[0][0] = 1 for i in range(1, n + 1): # Explicitly fill for j = 0 dp[i][0] = dp[i - 1][i - 1] # Fill for remaining values of j for j in range(1, i + 1): dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1] return dp[n][0] if __name__ == "__main__": n = 5 result = bellNumber(n) print(result)
C# // C# program to find n'th Bell number using System; class GfG { // Function to calculate the Bell number for a given // integer `n` static int BellNumber(int n) { int[, ] dp = new int[n + 1, n + 1]; dp[0, 0] = 1; for (int i = 1; i <= n; i++) { // Explicitly fill for j = 0 dp[i, 0] = dp[i - 1, i - 1]; // Fill for remaining values of j for (int j = 1; j <= i; j++) dp[i, j] = dp[i - 1, j - 1] + dp[i, j - 1]; } return dp[n, 0]; } static void Main(string[] args) { int n = 5; int result = BellNumber(n); Console.WriteLine(result); } }
Javascript // JavaScript program to find n'th Bell number // Function to calculate the Bell number for a given integer // `n` function bellNumber(n) { let dp = Array.from({length : n + 1}, () => Array(n + 1).fill(0)); dp[0][0] = 1; for (let i = 1; i <= n; i++) { // Explicitly fill for j = 0 dp[i][0] = dp[i - 1][i - 1]; // Fill for remaining values of j for (let j = 1; j <= i; j++) { dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]; } } return dp[n][0]; } let n = 5; let result = bellNumber(n); console.log(result);
Using Space Optimized DP - O(n^2) Time and O(n) Space
We can use a 1-D array to represent the previous row of the Bell triangle. We initialize dp[0] to 1, since there is only one way to partition an empty set.
To compute the Bell numbers for n > 0, we first set dp[0] = dp[i-1], since the first element in each row is the same as the last element in the previous row. Then, we use the recurrence relation dp[j] = prev + dp[j-1] to compute the Bell number for each partition, where prev is the value of dp[j] in the previous iteration of the inner loop. We update prev to the temporary variable temp before updating dp[j]. Finally, we return dp[0], which is the Bell number for the partition of a set with n elements into non-empty subsets.
C++ // C++ program to find n'th Bell number using // tabulation #include <iostream> #include <vector> using namespace std; // Function to calculate the Bell number for 'n' int bellNumber(int n) { // Initialize the previous row of the Bell triangle with // dp[0] = 1 vector<int> dp(n + 1, 0); dp[0] = 1; for (int i = 1; i <= n; i++) { // The first element in each row is the same as the // last element in the previous row int prev = dp[0]; dp[0] = dp[i - 1]; for (int j = 1; j <= i; j++) { // The Bell number for n is the sum of the Bell // numbers for all previous partitions int temp = dp[j]; dp[j] = prev + dp[j - 1]; prev = temp; } } return dp[0]; } int main() { int n = 5; cout << bellNumber(n) << std::endl; return 0; }
Java // Java program to find n'th Bell number using // tabulation import java.util.Arrays; class GfG { // Function to calculate the Bell number for 'n' static int bellNumbers(int n) { // Initialize the previous row of the Bell triangle // with dp[0] = 1 int[] dp = new int[n + 1]; Arrays.fill(dp, 0); dp[0] = 1; for (int i = 1; i <= n; i++) { // The first element in each row is the same as // the last element in the previous row int prev = dp[0]; dp[0] = dp[i - 1]; for (int j = 1; j <= i; j++) { // The Bell number for n is the sum of the // Bell numbers for all previous partitions int temp = dp[j]; dp[j] = prev + dp[j - 1]; prev = temp; } } return dp[0]; } public static void main(String[] args) { int n = 5; System.out.println(bellNumbers(n)); } }
Python # Python program to find n'th Bell number using # tabulation def bell_numbers(n): # Initialize the previous row of the # Bell triangle with dp[0] = 1 dp = [1] + [0] * n for i in range(1, n + 1): # The first element in each row is the same # as the last element in the previous row prev = dp[0] dp[0] = dp[i - 1] for j in range(1, i + 1): # The Bell number for n is the sum of the # Bell numbers for all previous partitions temp = dp[j] dp[j] = prev + dp[j - 1] prev = temp return dp[0] n = 5 print(bell_numbers(n))
C# // C# program to find n'th Bell number using // tabulation using System; class GfG { // Function to calculate the Bell number for 'n' static int BellNumbers(int n) { // Initialize the previous row of the Bell triangle // with dp[0] = 1 int[] dp = new int[n + 1]; dp[0] = 1; for (int i = 1; i <= n; i++) { // The first element in each row is the same as // the last element in the previous row int prev = dp[0]; dp[0] = dp[i - 1]; for (int j = 1; j <= i; j++) { // The Bell number for n is the sum of the // Bell numbers for all previous partitions int temp = dp[j]; dp[j] = prev + dp[j - 1]; prev = temp; } } return dp[0]; } static void Main() { int n = 5; Console.WriteLine(BellNumbers(n)); } }
Javascript // JavaScript program to find n'th Bell number using // tabulation function bellNumbers(n) { // Create an array to store intermediate values, // initialized with zeros let dp = new Array(n + 1).fill(0); // The first element represents the Bell number for 0, // which is 1 dp[0] = 1; // Iterate through each row of the Bell triangle up to // 'n' for (let i = 1; i <= n; i++) { // Store the value of the first element in the // current row let prev = dp[0]; // Update the first element of the row using the // last element of the previous row dp[0] = dp[i - 1]; // Iterate through each element in the current row for (let j = 1; j <= i; j++) { // Store the current value of dp[j] in a // temporary variable let temp = dp[j]; // Update dp[j] by adding the previous value // (prev) and the value at dp[j-1] dp[j] = prev + dp[j - 1]; // Update the 'prev' variable for the next // iteration of the inner loop prev = temp; } } // Return the Bell number for 'n' return dp[0]; } let n = 5; console.log(bellNumbers(n));
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 notGiven 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 notGiven 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 notGiven 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 7Given 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 notGiven 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 notGiven a number in the form of string s, 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: s = "76945"Output: trueExplanation: s when divided by 11 gives 0 as remainder.Input: s = "7695"Out
5 min read
Divisibility by 12 for a large numberGiven 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 larger number is divisible by 13 or notGiven a number s represented as a string, determine whether the integer it represents is divisible by 13 or not.Examples : Input: s = "2911285"Output: trueExplanation: 2911285 ÷ 13 = 223945, which is a whole number with no remainder.Input: s = "920"Output: falseExplanation: 920 ÷ 13 = 70.769..., whi
10 min read
Check if a large number is divisibility by 15Given 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 notGiven 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 elementsIn 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) numbersGiven 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 GCDStein'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 PropertyGiven 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 BGiven 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 numbersThe 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 nGiven integers n and m, construct a strictly increasing sequence of m positive integers with sum exactly equal to n such that the GCD of the sequence is maximized. If multiple sequences have the same maximum GCD, return the lexicographically smallest one. If not possible, return -1.Examples : Input
7 min read
Largest Subset with GCD 1Given 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 nGiven 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 SequenceJuggler 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 SequencePadovan 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 SequenceGiven 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 SequenceGiven 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 SequenceStern 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 SequenceNewman-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 sequenceIn 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 sequenceGiven 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)^2Given 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 termsGiven 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 SquareGiven 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 integerGiven 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 baseGiven 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 DisplayA 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 digitsGiven 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 notWrite 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 sYou 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 rangeGiven 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
3 min read
Algebra
Program to add two polynomialsGiven 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 polynomialsGiven 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 variablesGiven 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 ValueIn 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 vectorsThere 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 CoefficientThe 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 MethodGiven 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 = nGiven 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 TripletsGiven 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 numberGiven 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 methodThis 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 numberGiven 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 conversionGiven 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 StringGiven 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 versaGiven 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 operatorsFind 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 | ExamplesPrime 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 PrimeA 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 NMersenne 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 PrimeGiven 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 TheoremHardy 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 TheoremIn 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 theoremFermat'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 MethodGiven 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 TestVantieghems 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 TestThere 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 TestA 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 numberGiven 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 NumberGiven 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 NumberA 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 NumberGiven 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 numberGiven 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 FactorizationGiven 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 Positive NumberGiven a positive integer n, find all the distinct divisors of n.Examples:Input: n = 10 Output: [1, 2, 5, 10]Explanation: 1, 2, 5 and 10 are the divisors of 10. Input: n = 100Output: [1, 2, 4, 5, 10, 20, 25, 50, 100]Explanation: 1, 2, 4, 5, 10, 20, 25, 50 and 100 are divisors of 100.Table of Content[
7 min read
Find numbers with n-divisors in a given rangeGiven 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)Given three integers x, n, and M, compute (x^n) % M (remainder when x raised to the power n is divided by M).Examples : Input: x = 3, n = 2, M = 4Output: 1Explanation: 32 % 4 = 9 % 4 = 1.Input: x = 2, n = 6, M = 10Output: 4Explanation: 26 % 10 = 64 % 10 = 4.Table of Content[Naive Approach] Repeated
6 min read
Modular multiplicative inverseGiven 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 DivisionGiven three positive integers a, b, and M, the objective is to find (a/b) % M i.e., find the value of (a à b-1 ) % M, where b-1 is the modular inverse of b modulo M.Examples: Input: a = 10, b = 2, M = 13Output: 5Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 à 7) % 13 =
13 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 numberGiven 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