Split the given string into Primes : Digit DP | Function to check whether a string is a prime number or not ; A recursive function to find the minimum number of segments the given string can be divided such that every segment is a prime ; If the number is null ; checkPrime function is called to check if the number is a prime or not . ; A very large number denoting maximum ; Consider a minimum of 6 and length since the primes are less than 10 ^ 6 ; Recursively call the function to check for the remaining string ; Evaluating minimum splits into Primes for the suffix ; Checks if no combination found ; Driver code
function checkPrime ( number ) { let num = String ( number ) ; for ( let i = 2 ; i * i <= num ; i ++ ) if ( ( num % i ) == 0 ) return false ; return true ; } function splitIntoPrimes ( number ) { if ( number . length == 0 ) return 0 ; if ( number . length <= 6 && checkPrime ( number ) ) return 1 ; else { let numLen = number . length ; let ans = 1000000 ; for ( let i = 1 ; i <= 6 && i <= numLen ; i ++ ) { if ( checkPrime ( number . substr ( 0 , i ) ) ) { let val = splitIntoPrimes ( number . substr ( i ) ) ; if ( val != - 1 ) { ans = Math . min ( ans , 1 + val ) ; } } } if ( ans == 1000000 ) return - 1 ; return ans ; } } document . write ( splitIntoPrimes ( " " ) + " " ) ; document . write ( splitIntoPrimes ( " " ) + " " ) ;