Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- /*
- Logic:
- ->Using Sieve of erathosness,stored all the prime numbers in string
- data type in a map.
- ->dp array will store the minimum segment possible ie. dp[i]=minimum
- segment possible till ith index.
- ->It's must to have a prime from 0th index to ith index where i<=5
- otherwise that part will not be prime and answer will be -1.
- ->let's say there is prime number form lth to rth index,then go
- from (r+1)th index to (r+i)th index where i<=6 and check if that
- if prime then update the dp array.
- */
- void sieve(unordered_map<string,int> &primes){
- bool prime[1000001];
- memset(prime, true, sizeof(prime));
- prime[0] = prime[1] = false;
- for (int i = 2; i * i <= 1000000; i++) {
- if (prime[i] == true) {
- for (int j = i * i; j <= 1000000; j += i)
- prime[j] = false;
- }
- }
- for (int i = 2; i <= 1000000; i++) {
- if (prime[i] == true){
- primes[to_string(i)]=1;
- }
- }
- }
- int splitIntoPrimes(string number){
- int n= number.length();
- int dp[n + 1];
- memset(dp, -1, sizeof(dp));
- unordered_map<string,int>primes;
- sieve(primes);
- for (int i = 1; i <= n; i++) {
- if (i <= 6 && primes[number.substr(0, i)]){
- dp[i] = 1;
- }
- if (dp[i]!=-1) {
- for (int j = 1; j <= 6 && i + j <= n; j++) {
- if (primes[number.substr(i, j)]){
- if (dp[i + j]==-1)
- dp[i + j] = 1 + dp[i];
- else
- dp[i + j] = min(dp[i + j],1 + dp[i]);
- }
- }
- }
- }
- return dp[n];
- }
- int main(){
- cout << splitIntoPrimes("13499315") << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement