Minimum splits required to convert a number into prime segments
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
This problem is a variation of Matrix Chain Multiplication and can be solved using Dynamic programming.
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 returns 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 an 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:
Time Complexity: O(n3/2)
Auxiliary Space: O(106)
Please Login to comment...