Advertisement
imashutosh51

Split the string into prime segments

Aug 14th, 2022
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. /*
  4. Logic:
  5. ->Using Sieve of erathosness,stored all the prime numbers in string
  6.   data type in a map.
  7.  ->dp array will store the minimum segment possible ie. dp[i]=minimum
  8.    segment possible till ith index.
  9.  ->It's must to have a prime from 0th index to ith index where i<=5
  10.    otherwise that part will not be prime and answer will be -1.
  11.  ->let's say there is prime number form lth to rth index,then go
  12.    from (r+1)th index to (r+i)th index where i<=6 and check if that
  13.    if prime then update the dp array.
  14. */
  15. void sieve(unordered_map<string,int> &primes){
  16.     bool prime[1000001];
  17.     memset(prime, true, sizeof(prime));
  18.     prime[0] = prime[1] = false;
  19.     for (int i = 2; i * i <= 1000000; i++) {
  20.         if (prime[i] == true) {
  21.             for (int j = i * i; j <= 1000000; j += i)
  22.                 prime[j] = false;
  23.         }
  24.     }
  25.     for (int i = 2; i <= 1000000; i++) {
  26.         if (prime[i] == true){
  27.             primes[to_string(i)]=1;
  28.         }
  29.     }
  30. }
  31. int splitIntoPrimes(string number){
  32.     int n= number.length();
  33.     int dp[n + 1];
  34.     memset(dp, -1, sizeof(dp));
  35.     unordered_map<string,int>primes;
  36.     sieve(primes);  
  37.     for (int i = 1; i <= n; i++) {
  38.         if (i <= 6 && primes[number.substr(0, i)]){
  39.             dp[i] = 1;
  40.         }
  41.         if (dp[i]!=-1) {
  42.             for (int j = 1; j <= 6 && i + j <= n; j++) {
  43.                 if (primes[number.substr(i, j)]){
  44.                     if (dp[i + j]==-1)
  45.                         dp[i + j] = 1 + dp[i];
  46.                     else
  47.                         dp[i + j] = min(dp[i + j],1 + dp[i]);
  48.                 }
  49.             }
  50.         }
  51.     }
  52.     return dp[n];
  53. }
  54. int main(){
  55.     cout << splitIntoPrimes("13499315") << "\n";
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement