Given a string str that represents a large number, the task is to find the minimum number of segments the given string can be divided such that each segment is a prime number in the range of 1 to 106.
Examples:
Input: str = “13499315”
Output: 3
Explanation:
The number can be segmented as [13499, 31, 5]Input: str = “43”
Output: 1
Explanation:
The number can be segmented as [43]
Naive Approach: The idea is to consider every prefix up to 6 digits( Since it is given that the primes are less than 106) and check if it is a prime number or not. If the prefix is a prime number, then recursively call the function to check the remaining string. If a non-negative number is returned, then it is considered as a possible arrangement. If none of the possible combinations returns a positive number, then -1 is printed.
Below is the implementation of the above approach:
C++
| // C++ implementation of the above approach#include <iostream>#include <string>usingnamespacestd;// Function to check whether a string// is a prime number or notboolcheckPrime(string number){    intnum = stoi(number);    for(inti = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;}// A recursive function to find the minimum// number of segments the given string can// be divided such that every segment is a primeintsplitIntoPrimes(string number){    // If the number is null    if(number.length() == 0)        return0;    // checkPrime function is called to check if    // the number is a prime or not.    if(number.length() <= 6 and checkPrime(number))        return1;    else{        intnumLen = number.length();        // A very large number denoting maximum        intans = 1000000;        // Consider a minimum of 6 and length        // since the primes are less than 10 ^ 6        for(inti = 1; i <= 6 && i <= numLen; i++) {            if(checkPrime(number.substr(0, i))) {                // Recursively call the function                // to check for the remaining string                intval = splitIntoPrimes(number.substr(i));                if(val != -1) {                    // Evaluating minimum splits                    // into Primes for the suffix                    ans = min(ans, 1 + val);                }            }        }        // Checks if no combination found        if(ans == 1000000)            return-1;        returnans;    }}// Driver codeintmain(){    cout << splitIntoPrimes("13499315") << "\n";    cout << splitIntoPrimes("43") << "\n";    return0;} | 
Java
| // Java implementation of the above approachimportjava.util.*;classGFG{ // Function to check whether a String// is a prime number or notstaticbooleancheckPrime(String number){    intnum = Integer.valueOf(number);    for(inti = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;} // A recursive function to find the minimum// number of segments the given String can// be divided such that every segment is a primestaticintsplitIntoPrimes(String number){    // If the number is null    if(number.length() == 0)        return0;     // checkPrime function is called to check if    // the number is a prime or not.    if(number.length() <= 6&& checkPrime(number))        return1;     else{        intnumLen = number.length();         // A very large number denoting maximum        intans = 1000000;         // Consider a minimum of 6 and length        // since the primes are less than 10 ^ 6        for(inti = 1; i <= 6&& i <= numLen; i++) {            if(checkPrime(number.substring(0, i))) {                 // Recursively call the function                // to check for the remaining String                intval = splitIntoPrimes(number.substring(i));                if(val != -1) {                     // Evaluating minimum splits                    // into Primes for the suffix                    ans = Math.min(ans, 1+ val);                }            }        }         // Checks if no combination found        if(ans == 1000000)            return-1;        returnans;    }} // Driver codepublicstaticvoidmain(String[] args){    System.out.print(splitIntoPrimes("13499315")+ "\n");    System.out.print(splitIntoPrimes("43")+ "\n");}}// This code is contributed by Rajput-Ji | 
Python3
| # Python3 implementation of the above approach# Function to check whether a string # is a prime number or notdefcheckPrime(number) :          num =int(number)      fori inrange(2, int(num**0.5)) :            if((num %i) ==0) :                 returnFalse      returnTrue# A recursive function to find the minimum# number of segments the given string can # be divided such that every segment is a primedefsplitIntoPrimes(number) :      # If the number is null      if( number =='' ) :           return0      # checkPrime function is called to check if       # the number is a prime or not.      if( len(number)<=6andcheckPrime(number) ) :             return1      else:           numLen =len(number)           # A very large number denoting maximum           ans =1000000           # Consider a minimum of 6 and length            # since the primes are less than 10 ^ 6           fori inrange( 1, (min( 6, numLen ) +1) ) :                     if( checkPrime( number[:i] ) ) :                        # Recursively call the function                        # to check for the remaining string                        val =splitIntoPrimes( number[i:] )                        if(val !=-1) :                               # Evaluating minimum splits                                # into Primes for the suffix                                ans =min(ans, 1+val)                   # Checks if no combination found             if( ans ==1000000) :                    return-1           returnans           # Driver codeprint(splitIntoPrimes("13499315"))print(splitIntoPrimes("43")) | 
C#
| // C# implementation of the above approachusingSystem;classGFG{  // Function to check whether a String// is a prime number or notstaticboolcheckPrime(String number){    intnum = Int32.Parse(number);    for(inti = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;}  // A recursive function to find the minimum// number of segments the given String can// be divided such that every segment is a primestaticintsplitIntoPrimes(String number){    // If the number is null    if(number.Length == 0)        return0;      // checkPrime function is called to check if    // the number is a prime or not.    if(number.Length <= 6 && checkPrime(number))        return1;      else{        intnumLen = number.Length;          // A very large number denoting maximum        intans = 1000000;          // Consider a minimum of 6 and length        // since the primes are less than 10 ^ 6        for(inti = 1; i <= 6 && i <= numLen; i++) {            if(checkPrime(number.Substring(0, i))) {                  // Recursively call the function                // to check for the remaining String                intval = splitIntoPrimes(number.Substring(i));                if(val != -1) {                      // Evaluating minimum splits                    // into Primes for the suffix                    ans = Math.Min(ans, 1 + val);                }            }        }          // Checks if no combination found        if(ans == 1000000)            return-1;        returnans;    }}  // Driver codepublicstaticvoidMain(String[] args){    Console.Write(splitIntoPrimes("13499315")+ "\n");    Console.Write(splitIntoPrimes("43")+ "\n");}}// This code is contributed by sapnasingh4991 | 
Javascript
| <script>// JavaScript implementation of the above approach// Function to check whether a string// is a prime number or notfunctioncheckPrime(number){    let num = String(number);    for(let i = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;}// A recursive function to find the minimum// number of segments the given string can// be divided such that every segment is a primefunctionsplitIntoPrimes(number){    // If the number is null    if(number.length == 0)        return0;    // checkPrime function is called to check if    // the number is a prime or not.    if(number.length <= 6 && checkPrime(number))        return1;    else{        let numLen = number.length;        // A very large number denoting maximum        let ans = 1000000;        // Consider a minimum of 6 and length        // since the primes are less than 10 ^ 6        for(let i = 1; i <= 6 && i <= numLen; i++) {            if(checkPrime(number.substr(0, i))) {                // Recursively call the function                // to check for the remaining string                let val = splitIntoPrimes(number.substr(i));                if(val != -1) {                    // Evaluating minimum splits                    // into Primes for the suffix                    ans = Math.min(ans, 1 + val);                }            }        }        // Checks if no combination found        if(ans == 1000000)            return-1;        returnans;    }}// Driver codedocument.write(splitIntoPrimes("13499315") + "<br>");document.write(splitIntoPrimes("43") + "<br>");// This code is contributed by gfgking</script> | 
3 1
Time Complexity:
- The time complexity for the above approach would be of O(N5/2) where N is the length of the input string.
- The complexity to find all the possible combinations recursively is O(N2).
- For every combination, to check if the number is a prime number or not, an additional O(N0.5) time is used.
- This makes the time complexity O(N5/2).
Dynamic Programming Approach: The given problem is seen to exhibit an overlapping subproblem property. Therefore, dynamic programming can be used to efficiently solve this question. 
A splitDP[] array is defined and used where splitDP[i] denotes the minimum number of splits required in the prefix string of length ‘i’ to break it into the prime subdivision. 
The splitDP[] array is filled in the following way: 
- A for loop is used to iterate through all the indices of the given string.
- For every index ‘i’ from the above loop, another loop is iterated from 1 to 6 to check if the substring from (i + j)th index forms a prime or not.
- If it forms a prime number, then the value at splitDP[] is updated as:
splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]);
- After updating all the values of the array, the value at the last index is the minimum number of splits for the entire string.
Below is the implementation of the above approach:
C++
| // C++ implementation of the above approach#include <bits/stdc++.h>usingnamespacestd;// Function to check whether a string// is a prime number or notboolcheckPrime(string number){    intnum = stoi(number);    for(inti = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;}// A function to find the minimum// number of segments the given string// can be divided such that every// segment is a primeintsplitIntoPrimes(string number){    intnumLen = number.length();    // Declare a splitdp[] array    // and initialize to -1    intsplitDP[numLen + 1];    memset(splitDP, -1, sizeof(splitDP));    // Build the DP table in    // a bottom-up manner    for(inti = 1; i <= numLen; i++) {        // Initially Check if the entire prefix is Prime        if(i <= 6 && checkPrime(number.substr(0, i)))            splitDP[i] = 1;        // If the Given Prefix can be split into Primes        // then for the remaining string from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1) {            for(intj = 1; j <= 6 && i + j <= numLen; j++) {                // To check if the substring from i to j                // is a prime number or not                if(checkPrime(number.substr(i, j))) {                    // If it is a prime, then update the dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1 + splitDP[i];                    else                        splitDP[i + j] = min(splitDP[i + j],                                             1 + splitDP[i]);                }            }        }    }    // Return the minimum number of splits    // for the entire string    returnsplitDP[numLen];}// Driver codeintmain(){    cout << splitIntoPrimes("13499315") << "\n";    cout << splitIntoPrimes("43") << "\n";    return0;} | 
Java
| // Java implementation of the above approachimportjava.util.*;classGFG{ // Function to check whether a String// is a prime number or notstaticbooleancheckPrime(String number){    if(number.length()==0)        returntrue;    intnum = Integer.parseInt(number);    for(inti = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestaticintsplitIntoPrimes(String number){    intnumLen = number.length();     // Declare a splitdp[] array    // and initialize to -1    int[]splitDP = newint[numLen + 1];    Arrays.fill(splitDP, -1);     // Build the DP table in    // a bottom-up manner    for(inti = 1; i <= numLen; i++) {         // Initially Check if the entire prefix is Prime        if(i <= 6&& checkPrime(number.substring(0, i)))            splitDP[i] = 1;         // If the Given Prefix can be split into Primes        // then for the remaining String from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1) {            for(intj = 1; j <= 6&& i + j <= numLen; j++) {                 // To check if the subString from i to j                // is a prime number or not                if(checkPrime(number.substring(i, i+j))) {                     // If it is a prime, then update the dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1+ splitDP[i];                    else                        splitDP[i + j] = Math.min(splitDP[i + j],                                             1+ splitDP[i]);                }            }        }    }     // Return the minimum number of splits    // for the entire String    returnsplitDP[numLen];} // Driver codepublicstaticvoidmain(String[] args){    System.out.print(splitIntoPrimes("13499315")+ "\n");    System.out.print(splitIntoPrimes("43")+ "\n");}}// This code contributed by Princi Singh | 
Python3
| # Python 3 implementation of the above approachfrommath importsqrt# Function to check whether a string# is a prime number or notdefcheckPrime(number):    if(len(number) ==0):        returnTrue    num =int(number)    fori inrange(2,int(sqrt(num)) +1, 1):        if((num %i) ==0):            returnFalse    returnTrue# A function to find the minimum# number of segments the given string# can be divided such that every# segment is a primedefsplitIntoPrimes(number):    numLen =len(number)    # Declare a splitdp[] array    # and initialize to -1    splitDP =[-1fori inrange(numLen +1)]    # Build the DP table in    # a bottom-up manner    fori inrange(1, numLen +1, 1):        # Initially Check if the entire prefix is Prime        if(i <=6andcheckPrime(number[0:i])):            splitDP[i] =1        # If the Given Prefix can be split into Primes        # then for the remaining string from i to j        # Check if Prime. If yes calculate        # the minimum split till j        if(splitDP[i] !=-1):            j =1            while(j <=6andi +j <=numLen):                # To check if the substring from i to j                # is a prime number or not                if(checkPrime(number[i:i+j])):                    # If it is a prime, then update the dp array                    if(splitDP[i +j] ==-1):                        splitDP[i +j] =1+splitDP[i]                    else:                        splitDP[i +j] =min(splitDP[i +j], 1+splitDP[i])                j +=1    # Return the minimum number of splits    # for the entire string    returnsplitDP[numLen]# Driver codeif__name__ =='__main__':    print(splitIntoPrimes("13499315"))    print(splitIntoPrimes("43"))# This code is contributed by Surendra_Gangwar | 
C#
| // C# implementation of the above approachusingSystem;classGFG{  // Function to check whether a String// is a prime number or notstaticboolcheckPrime(String number){    if(number.Length==0)        returntrue;    intnum = Int32.Parse(number);    for(inti = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;    returntrue;}  // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestaticintsplitIntoPrimes(String number){    intnumLen = number.Length;      // Declare a splitdp[] array    // and initialize to -1    int[]splitDP = newint[numLen + 1];    for(inti = 0; i <= numLen; i++)        splitDP[i] = -1;      // Build the DP table in    // a bottom-up manner    for(inti = 1; i <= numLen; i++) {          // Initially Check if the entire prefix is Prime        if(i <= 6 && checkPrime(number.Substring(0, i)))            splitDP[i] = 1;          // If the Given Prefix can be split into Primes        // then for the remaining String from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1) {            for(intj = 1; j <= 6 && i + j <= numLen; j++) {                  // To check if the subString from i to j                // is a prime number or not                if(checkPrime(number.Substring(i, j))) {                      // If it is a prime, then update the dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1 + splitDP[i];                    else                        splitDP[i + j] = Math.Min(splitDP[i + j],                                             1 + splitDP[i]);                }            }        }    }      // Return the minimum number of splits    // for the entire String    returnsplitDP[numLen];}  // Driver codepublicstaticvoidMain(String[] args){    Console.Write(splitIntoPrimes("13499315")+ "\n");    Console.Write(splitIntoPrimes("43")+ "\n");}}// This code is contributed by Rajput-Ji | 
Javascript
| <script>// Javascript implementation of the above approach// Function to check whether a String// is a prime number or notfunctioncheckPrime(number){    if(number.length == 0)        returntrue;            let num = parseInt(number);    for(let i = 2; i * i <= num; i++)        if((num % i) == 0)            returnfalse;                returntrue;}// A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primefunctionsplitIntoPrimes(number){    let numLen = number.length;       // Declare a splitdp[] array    // and initialize to -1    let splitDP = newArray(numLen + 1);    for(let i = 0; i < splitDP.length; i++)    {        splitDP[i] = -1;    }       // Build the DP table in    // a bottom-up manner    for(let i = 1; i <= numLen; i++)    {                // Initially Check if the entire prefix is Prime        if(i <= 6 && checkPrime(number.substring(0, i)))            splitDP[i] = 1;           // If the Given Prefix can be split into Primes        // then for the remaining String from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1)        {            for(let j = 1;                     j <= 6 && i + j <= numLen;                     j++)             {                   // To check if the subString from i to j                // is a prime number or not                if(checkPrime(number.substring(i, i + j)))                 {                                        // If it is a prime, then update the                     // dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1 + splitDP[i];                    else                        splitDP[i + j] = Math.min(                            splitDP[i + j],                                    1 + splitDP[i]);                }            }        }    }       // Return the minimum number of splits    // for the entire String    returnsplitDP[numLen];}// Driver codedocument.write(splitIntoPrimes("13499315") + "<br>");document.write(splitIntoPrimes("43") + "<br>");// This code is contributed by avanitrachhadiya2155</script> | 
3 1
Time Complexity:
- The time complexity of the above approach is O(N3/2) where N is the length of the input string.
- The time to iterate through all the indices is O(N).
- Since the inner for loop runs a constant number of times for every index, it’s run time can be considered as constant.
- For every index, the time taken to check whether the number is a prime or not is of O(N0.5).
- Therefore, the overall time complexity is O(N3/2).
Optimized Dynamic Programming Approach: The above approach can further be optimized by using the concept Sieve of Eratosthenes to precompute and store whether a number is prime or not and reducing the time complexity to check for a number at every iteration.
Below is the implementation of the above approach:
C++
| // C++ implementation of the above approach#include <bits/stdc++.h>usingnamespacestd;// Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of EratosthenesvoidgetPrimesFromSeive(set<string>& primes){    boolprime[1000001];    memset(prime, true, sizeof(prime));    prime[0] = prime[1] = false;    for(inti = 2; i * i <= 1000000; i++) {        if(prime[i] == true) {            for(intj = i * i; j <= 1000000; j += i)                prime[j] = false;        }    }    // Here to_string() is used    // for converting int to string    for(inti = 2; i <= 1000000; i++) {        if(prime[i] == true)            primes.insert(to_string(i));    }}// A function to find the minimum// number of segments the given string// can be divided such that every// segment is a primeintsplitIntoPrimes(string number){    intnumLen = number.length();    // Declare a splitdp[] array    // and initialize to -1    intsplitDP[numLen + 1];    memset(splitDP, -1, sizeof(splitDP));    // Call sieve function to store primes in    // primes array    set<string> primes;    getPrimesFromSeive(primes);    // Build the DP table in a bottom-up manner    for(inti = 1; i <= numLen; i++) {        // If the prefix is prime then the prefix        // will be found in the prime set        if(i <= 6 && (primes.find(number.substr(0, i))                       != primes.end()))            splitDP[i] = 1;        // If the Given Prefix can be split into Primes        // then for the remaining string from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1) {            for(intj = 1; j <= 6 && i + j <= numLen; j++) {                // To check if the substring from i to j                // is a prime number or not                if(primes.find(number.substr(i, j))                    != primes.end()) {                    // If it is a prime, then update the dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1 + splitDP[i];                    else                        splitDP[i + j] = min(splitDP[i + j],                                             1 + splitDP[i]);                }            }        }    }    // Return the minimum number of splits    // for the entire string    returnsplitDP[numLen];}intmain(){    cout << splitIntoPrimes("13499315") << "\n";    cout << splitIntoPrimes("43") << "\n";    return0;} | 
Java
| // Java implementation of the above approachimportjava.util.*;classGFG{ // Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of EratosthenesstaticvoidgetPrimesFromSeive(HashSet<String> primes){    boolean[]prime = newboolean[1000001];    Arrays.fill(prime, true);    prime[0] = prime[1] = false;    for(inti = 2; i * i <= 1000000; i++) {        if(prime[i] == true) {            for(intj = i * i; j <= 1000000; j += i)                prime[j] = false;        }    }     // Here to_String() is used    // for converting int to String    for(inti = 2; i <= 1000000; i++) {        if(prime[i] == true)            primes.add(String.valueOf(i));    }} // A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestaticintsplitIntoPrimes(String number){    intnumLen = number.length();     // Declare a splitdp[] array    // and initialize to -1    int[]splitDP = newint[numLen + 1];    Arrays.fill(splitDP, -1);     // Call sieve function to store primes in    // primes array    HashSet<String> primes = newHashSet<String>();    getPrimesFromSeive(primes);     // Build the DP table in a bottom-up manner    for(inti = 1; i <= numLen; i++) {         // If the prefix is prime then the prefix        // will be found in the prime set        if(i <= 6&& (primes.contains(number.substring(0, i))))            splitDP[i] = 1;         // If the Given Prefix can be split into Primes        // then for the remaining String from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1) {            for(intj = 1; j <= 6&& i + j <= numLen; j++) {                 // To check if the subString from i to j                // is a prime number or not                if(primes.contains(number.substring(i, i+j))) {                     // If it is a prime, then update the dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1+ splitDP[i];                    else                        splitDP[i + j] = Math.min(splitDP[i + j],                                             1+ splitDP[i]);                }            }        }    }     // Return the minimum number of splits    // for the entire String    returnsplitDP[numLen];} publicstaticvoidmain(String[] args){    System.out.print(splitIntoPrimes("13499315")+ "\n");    System.out.print(splitIntoPrimes("43")+ "\n");}}// This code contributed by Princi Singh | 
Python3
| # Python3 implementation of the above approach# Function to precompute all the primes# upto 1000000 and store it in a set# using Sieve of EratosthenesdefgetPrimesFromSeive(primes):    prime =[True] *(1000001)    prime[0], prime[1] =False, False    i =2    while(i *i <=1000000):        if(prime[i] ==True):            forj inrange(i *i, 1000001, i):                prime[j] =False        i +=1    # Here str() is used for    # converting int to string    fori inrange(2, 1000001):        if(prime[i] ==True):            primes.append(str(i))# A function to find the minimum# number of segments the given string# can be divided such that every# segment is a primedefsplitIntoPrimes(number):    numLen =len(number)    # Declare a splitdp[] array    # and initialize to -1    splitDP =[-1] *(numLen +1)    # Call sieve function to store     # primes in primes array    primes =[]    getPrimesFromSeive(primes)    # Build the DP table in a bottom-up manner    fori inrange(1, numLen +1):        # If the prefix is prime then the prefix        # will be found in the prime set        if(i <=6and(number[0: i] inprimes)):            splitDP[i] =1        # If the Given Prefix can be split into Primes        # then for the remaining string from i to j        # Check if Prime. If yes calculate        # the minimum split till j        if(splitDP[i] !=-1):            j =1            while(j <=6and(i +j <=numLen)):                # To check if the substring from i to j                # is a prime number or not                if(number[i : i +j] inprimes):                    # If it is a prime, then                     # update the dp array                    if(splitDP[i +j] ==-1):                        splitDP[i +j] =1+splitDP[i]                    else:                        splitDP[i +j] =min(splitDP[i +j],                                         1+splitDP[i])                                                            j +=1    # Return the minimum number of     # splits for the entire string    returnsplitDP[numLen]# Driver codeprint(splitIntoPrimes("13499315"))print(splitIntoPrimes("43"))# This code is contributed by chitranayal | 
C#
| // C# implementation of the above approachusingSystem;usingSystem.Collections.Generic;classGFG{// Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of EratosthenesstaticvoidgetPrimesFromSeive(HashSet<String> primes){    bool[]prime = newbool[1000001];        for(inti = 0; i < 1000001; i++)       prime[i] = true;    prime[0] = prime[1] = false;        for(inti = 2; i * i <= 1000000; i++)    {       if(prime[i] == true)       {           for(intj = i * i; j <= 1000000; j += i)              prime[j] = false;       }    }        // Converting int to String    for(inti = 2; i <= 1000000; i++)    {       if(prime[i] == true)           primes.Add(String.Join("", i));    }}// A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primestaticintsplitIntoPrimes(String number){    intnumLen = number.Length;    // Declare a splitdp[] array    // and initialize to -1    int[]splitDP = newint[numLen + 1];    for(inti = 0; i < numLen + 1; i++)       splitDP[i] = -1;    // Call sieve function to store primes     // in primes array    HashSet<String> primes = newHashSet<String>();    getPrimesFromSeive(primes);    // Build the DP table in a bottom-up manner    for(inti = 1; i <= numLen; i++)    {              // If the prefix is prime then the prefix       // will be found in the prime set       if(i <= 6 && (primes.Contains                     (number.Substring(0, i))))           splitDP[i] = 1;              // If the given prefix can be split into        // primes, then for the remaining String        // from i to j check if prime. If yes        // calculate the minimum split till j       if(splitDP[i] != -1)       {           for(intj = 1; j <= 6 && i + j <= numLen; j++)           {                         // To check if the subString from               // i to j is a prime number or not              if(primes.Contains(number.Substring(i, j)))              {                                    // If it is a prime, then update                  // the dp array                  if(splitDP[i + j] == -1)                      splitDP[i + j] = 1 + splitDP[i];                  else                      splitDP[i + j] = Math.Min(splitDP[i + j],                                            1 + splitDP[i]);              }           }       }    }    // Return the minimum number of     // splits for the entire String    returnsplitDP[numLen];}publicstaticvoidMain(String[] args){    Console.Write(splitIntoPrimes("13499315") + "\n");    Console.Write(splitIntoPrimes("43") + "\n");}}// This code is contributed by sapnasingh4991 | 
Javascript
| <script>// Javascript implementation of the above approach// Function to precompute all the primes// upto 1000000 and store it in a set// using Sieve of EratosthenesfunctiongetPrimesFromSeive(primes){    let prime = newArray(1000001);    for(let i=0;i<prime.length;i++)    {        prime[i]=true;    }    prime[0] = prime[1] = false;    for(let i = 2; i * i <= 1000000; i++) {        if(prime[i] == true) {            for(let j = i * i; j <= 1000000; j += i)                prime[j] = false;        }    }      // Here to_String() is used    // for converting int to String    for(let i = 2; i <= 1000000; i++) {        if(prime[i] == true)            primes.add((i).toString());    }}// A function to find the minimum// number of segments the given String// can be divided such that every// segment is a primefunctionsplitIntoPrimes(number){    let numLen = number.length;      // Declare a splitdp[] array    // and initialize to -1    let splitDP = newArray(numLen + 1);    for(let i=0;i<splitDP.length;i++)    {        splitDP[i]=-1;    }      // Call sieve function to store primes in    // primes array    let primes = newSet();    getPrimesFromSeive(primes);      // Build the DP table in a bottom-up manner    for(let i = 1; i <= numLen; i++) {          // If the prefix is prime then the prefix        // will be found in the prime set        if(i <= 6 && (primes.has(number.substring(0, i))))            splitDP[i] = 1;          // If the Given Prefix can be split into Primes        // then for the remaining String from i to j        // Check if Prime. If yes calculate        // the minimum split till j        if(splitDP[i] != -1) {            for(let j = 1; j <= 6 && i + j <= numLen; j++) {                  // To check if the subString from i to j                // is a prime number or not                if(primes.has(number.substring(i, i+j))) {                      // If it is a prime, then update the dp array                    if(splitDP[i + j] == -1)                        splitDP[i + j] = 1 + splitDP[i];                    else                        splitDP[i + j] = Math.min(splitDP[i + j],                                             1 + splitDP[i]);                }            }        }    }      // Return the minimum number of splits    // for the entire String    returnsplitDP[numLen];}document.write(splitIntoPrimes("13499315")+ "<br>");document.write(splitIntoPrimes("43")+ "<br>");// This code is contributed by rag2127</script> | 
3 1
Time Complexity:
- This is the most efficient method as this runs in O(N) time complexity where N is the length of the input string.
- Since the sieve of Eratosthenes has a run time of O(N*log(log(N))) and the list of primes up to 106, the precomputation complexity can be calculated. However, since this is performed only once for any number of strings, it is not counted in calculating time complexity.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







