Given two positive integers N and K, the task is to count all the numbers that satisfy the following conditions:
If the number is num,
- num ≤ N.
- abs(num – count) ≥ K where count is the count of primes upto num.
Input: N = 10, K = 3
6, 7, 8, 9 and 10 are the valid numbers. For 6, the difference between 6 and prime numbers upto 6 (2, 3, 5) is 3 i.e. 6 – 3 = 3. For 7, 8, 9 and 10 the differences are 3, 4, 5 and 6 respectively which are ≥ K.
Input: N = 30, K = 13
Prerequisite: Binary Search
Approach: Observe that the function which is the difference of the number and count of prime numbers upto that number is a monotonically increasing function for a particular K. Also, if a number X is a valid number then X + 1 will also be a valid number.
Let the function Ci denotes the count of prime numbers upto number i. Now,
for the number X + 1 the difference is X + 1 – CX + 1 which is greater than
or equal to the difference X – CX for the number X, i.e. (X + 1 – CX + 1) ≥ (X – CX).
Thus, if (X – CX) ≥ S, then (X + 1 – CX + 1) ≥ S.
Hence, we can use binary search to find the minimum valid number X and all the numbers from X to N will be valid numbers. So, the answer would be N – X + 1.
Below is the implementation of the above approach:
// Check if the number is
// valid, try to reduce it
if ($mid – $primeUpto[$mid] >= $K)
$ans = $mid;
$high = $mid – 1;
$low = $mid + 1;
// ans is the minimum valid number
return ($ans ? $N – $ans + 1 : 0);
// Driver Code
$N = 10;
$K = 3;
echo countOfNumbers($N, $K);
// This code is contributed by mits
- Count numbers which can be represented as sum of same parity primes
- Count primes that can be expressed as sum of two consecutive primes and 1
- Count numbers whose difference with N is equal to XOR with N
- Count numbers upto N which are both perfect square and perfect cube
- Count of Numbers such that difference between the number and sum of its digits not less than L
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Count numbers with difference between number and its digit sum greater than specific value
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Count Primes in Ranges
- Program to count number of distinct Squares and Cubes upto N
- Count the number of primes in the prefix sum array of the given array
- Count ways of choosing a pair with maximum difference
- Count maximum elements of an array whose absolute difference does not exceed K
- Count numbers that don't contain 3
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.