Given a number in the form of a string s, the task is to calculate and display minimum splits required such that the segments formed are Prime or print Not Possible otherwise.
Input: s = “2351”
Output : 0
Explanation: Given number is already prime.
Input: s = “2352”
Explanation: Resultant prime segments are 23,5,2
Input: s = “2375672”
Output : 2
Explanation: Resultant prime segments are 2,37567,2
Try all possible splits recursively and at each split, check whether the segments formed are prime or not. Consider a 2D array dp where dp[i][j] shows the minimum splits from index i to j and return dp[n] where n is the length of the string.
dp[i][j] = min(1 + solve(i, k) + solve(k + 1, j)) where i <= k <= j
Actually, in the exact recurrence written above, the left and right segments both are non-prime, then 1 + INT_MAX + INT_MAX will be negative which leads to incorrect answer.
So, separate calculations for the left and right segments are required. If any segment is found to be non-prime, no need to proceed further. Return min(1+left+right) otherwise.
Base cases considered are :
- If the number is prime, return 0
- If i==j and the number is prime, return 0
- If i==j and the number is not prime, return INT_MAX
Below code is the implementation of above approach:
- Minimum number of cuts required to make circle segments equal sized
- Minimum number operations required to convert n to m | Set-2
- Minimum number of given operation required to convert n to m
- Minimum number of subsequences required to convert one string to another
- Minimum number of subsequences required to convert one string to another using Greedy Algorithm
- Minimum prime number operations to convert A to B
- Minimum number of given operations required to convert a permutation into an identity permutation
- Minimum number of given operations required to convert a string to another string
- Minimum operations required to convert X to Y by multiplying X with the given co-primes
- Minimum swaps required to convert one binary string to another
- Minimum given operations required to convert a given binary string to all 1's
- Minimum operations required to convert a binary string to all 0s or all 1s
- Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
- Minimum splits in a binary string such that every substring is a power of 4 or 6.
- Number of steps required to convert a binary number to one