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 of Numbers such that difference between the number and sum of its digits not less than L
- Count numbers upto N which are both perfect square and perfect cube
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Count numbers with difference between number and its digit sum greater than specific value
- Count Primes in Ranges
- Program to count number of distinct Squares and Cubes upto N
- Count ways of choosing a pair with maximum difference
- Count numbers that don't contain 3
- Count Odd and Even numbers in a range from L to R
- Count numbers from 1 to n that have 4 as a digit
- Count numbers with same first and last digits
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N