KatInterview

Prime Segment Partitions of a Digit Sequence

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingprimality-teststrings

Last updated

Count the ways to cut a digit string into prime-valued pieces without leading zeros, using prefix dynamic programming plus a fast primality check, modulo 1,000,000,007.

Prime Segment Partitions of a Digit Sequence

You are given a string digits made up only of the characters '0' to '9'.

A cut plan divides digits into one or more non-empty, consecutive pieces that, placed side by side in order, give back the original string. A cut plan is acceptable when every piece satisfies all of the following:

  • Its first character is not '0' (so "7" is allowed, but "07" is not).
  • The integer it represents is a prime number.
  • The integer it represents is at most 10^9.

Count the acceptable cut plans for digits. Two plans are different if they cut at different positions. Because the count can be huge, return it modulo 1_000_000_007.

If no acceptable plan exists, return 0.

Notes

  • 0 and 1 are not prime, so pieces such as "0" or "1" are never allowed.
  • A piece longer than 9 digits is never allowed, because it would exceed 10^9.
  • A zero in the middle or at the end of a piece is fine, as in "307". Only a leading zero is forbidden.

Constraints

  • 1 <= len(digits) <= 1000
  • digits contains only the characters '0' through '9'.
  • The function returns an integer in the range [0, 1_000_000_006].

Examples

Example 1

Input: count_prime_cuts('113')

Output: 2

Example 2

Input: count_prime_cuts('3175')

Output: 3

Example 3

Input: count_prime_cuts('023')

Output: 0

Hints

Hint 1

Let ways[i] be the number of acceptable plans for the first i characters, with ways[0] = 1 for the empty prefix. How can the last piece of a plan help you compute ways[i]?

Hint 2

Every acceptable piece is a prime no larger than 10^9, and 10^9 itself is not prime, so no piece has more than 9 digits. From each start position you only need to test at most 9 end positions.

Hint 3

Skip any start position whose character is '0'. Test each candidate value for primality (trial division up to the square root, or Miller-Rabin, with optional caching), and take the modulus at every addition.