Sheldon Numbers
Time limit1sMemory limit256 MB
Count numbers between X and Y whose binary form starts with ones and alternates blocks of N ones and M zeros.
- Level
Medium5 of 10
- Topics
- Brute force, Bit manipulation, Binary search
- Solved
- No attempts yet
Problem
According to Sheldon Cooper, the best number is 73. In his own words: "The best number is 73. 73 is the 21st prime number. Its mirror, 37, is the 12th, and its mirror, 21, is the product of multiplying 7 and 3. In binary, 73 is a palindrome: 1001001, which backwards is 1001001. Exactly the same."
Prime numbers are familiar ground, and so are palindromes. The binary representation of 73 holds one more rule worth noting: 1 one, then 2 zeros, then 1 one, then 2 zeros, then 1 one. That rule generalizes. Put ones, then zeros, then ones, then zeros, and so on, ending in either a block of ones or a block of zeros. For 73, is 1, is 2, and there are 5 blocks of equal symbols. With , and 4 blocks you get the string 110110, which is the binary representation of 54.
This gives the notion of a Sheldon number: a positive integer whose binary representation matches the pattern or the pattern , where every occurrence of is a string of bits 1 and every occurrence of is a string of bits 0, with and . The representation must contain at least one occurrence of , but the number of occurrences of may be zero.
Many well known numbers are Sheldon numbers: 1755, the year of the great Lisbon earthquake, 1984, the title of Orwell's novel, and 2015. So is 21, which Sheldon mentions, and so is 42, the answer given by the computer Deep Thought to the Great Question of Life, the Universe and Everything.
There are infinitely many Sheldon numbers. Given two integers, write a program that counts the Sheldon numbers in the range they define.
Input
The input contains one line with two space separated integers and .
Output
Print one line with the number of Sheldon numbers that are greater than or equal to and less than or equal to .