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:
- Count numbers which can be represented as sum of same parity primes
- Count of Octal numbers upto N digits
- Count primes that can be expressed as sum of two consecutive primes and 1
- Count numbers upto N which are both perfect square and perfect cube
- Count of primes below N which can be expressed as the sum of two primes
- 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 with difference between number and its digit sum greater than specific value
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Queries for the difference between the count of composite and prime numbers in a given range
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Count Primes in Ranges
- Maximum count of common divisors of A and B such that all are co-primes to one another
- 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
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.