Given an integer N. The task is to count the number of ordered pairs (a, b) such that .
Input: N = 5 Output: 8 Ordered Pairs are = (1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1). Input: N = 1000 Output: 7053
Naive Approach: Run two for loops upto N – 1 and count ordered pairs whose product are less than N.
Efficient Approach: Let’s considered an ordered pair (a, b). Then, if the product of two numbers is less than n i:e a * b < n, then at least one of them must be less then square root of n. We can proof by contradiction that if both numbers are greater then square root of n the their product is not less than n.
So, you can take all integers a up to sqrt(n – 1) instead of all integers up to n. For each a, count the number of b >= a such that a * b < n. Then multiply the result by two to count the pair (b, a) for each pair (a, b) you saw. After that, subtract the integer part of sqrt(n – 1) to ensure the pairs (a, a) were counted exactly once.
Below is the implementation of the above approach:
Time Complexity: O(N*sqrt(N))
- Count number of ordered pairs with Even and Odd Product
- Count number of ordered pairs with Even and Odd Sums
- Count ordered pairs of positive numbers such that their sum is S and XOR is K
- Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two
- Count pairs of numbers from 1 to N with Product divisible by their Sum
- Count of pairs in an array such that the highest power of 2 that divides their product is 1
- Number of Co-prime pairs from 1 to N with product equals to N
- Number of pairs in an array having sum equal to product
- Count pairs with Odd XOR
- Count pairs with given sum | Set 2
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
- Count of pairs of (i, j) such that ((n % i) % j) % n is maximized
- Count number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j]
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N
- Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = 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.