Truncatable Primes
Time limit1sMemory limit512 MB
Count integers in [a, b] whose every prefix from the left is prime.
- Level
Medium7 of 10
- Topics
- Backtracking, Number theory
- Solved
- No attempts yet
Problem
Recall that a prime is a positive integer with exactly two distinct divisors: and itself. We say that a number is a prefix of a number if can be obtained by deleting some number of digits from the end of . For example, is a prefix of . A truncatable prime is a number all of whose prefixes of non-zero length are prime. For example, is a truncatable prime, because its non-empty prefixes and are both prime.
Given two positive integers , (), write a program that determines how many integers in the closed interval are truncatable primes.
Input
A single line of standard input contains two integers , (), separated by a space.
Output
Print a single integer: the number of truncatable primes that are not less than and not greater than .
Hint
There are only finitely many such numbers. The first digit must be one of the single-digit primes , , , , and every time you append a digit on the right the resulting number must still be prime. So you can generate all such numbers in advance and then count those that fall inside the interval.