A number N is given in the range 1 <= N <= 10^50
. A function F(x)
is defined as the sum of all digits of a number x. We have to find the count of number of special pairs (x, y) such that:
1. 0 <= x, y <= N
2. F(x) + F(y)
is prime in nature
We have to count (x, y)
and (y, x)
only once.
Print the output modulo 1000000000 + 7
My approach:
Since the maximum value of sum of digits in given range can be 450 (If all the characters are 9 in a number of length 50, which gives 9*50 = 450
). So, we can create a 2-D array of size 451*451 and for all pair we can store whether it is prime or not.
Now, the issue I am facing is to find all the pairs (x, y) for given number N in linear time (Obviously, we cannot loop through 10^50 to find all the pairs). Can someone suggest any approach, or any formula (if exists), to get all the pairs in linear time.
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- d3.js moving average with previous and next data v
- How to get a fixed number of evenly spaced points
相关文章
- What are the problems associated to Best First Sea
- ceil conterpart for Math.floorDiv in Java?
- Coin change DP solution to keep track of coins
- why 48 bit seed in util Random class?
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- Need help generating discrete random numbers from
You can create a 2-D array of size 451*451 and for all pair we can store whether it is prime or not. At the same time if you know how many numbers less than n who have F(x)=i and how many have F(x)=j, then after checking (i+j) is prime or not you can easily find a result with the state (i,j) of 2-D array of size 451*451.
So what you need is finding the total numbers who have F(x) =i.
You can easily do it using digit dp:
Digit DP for finding how many numbers who have F(x)=i:
This function will return the total numbers less than n who have F(x)=i.
So we can call this function for every i from 0 to 451 and can store the result in a temporary variable.
Now test for each pair (i,j) :
finally result will be answer/2 as (i,j) and (j,i) will be calculated once.
Here's the answer in Python if which makes the code easily readable and a bit easier to understand.
Thanks to @mahbubcseju for providing the solution to this problem.