Count triplets such that product of two numbers added with third number is N
Given a positive integer N, the task is to find the number of triplets (A, B, C) where A, B, C are positive integers such that the product of two numbers added with the third number is N i.e., A * B + C = N.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 3
Following are the possible triplets satisfying the given criteria:
- (1, 1, 2): The value of 1*1 + 2 = 3.
- (1, 2, 1): The value of 1*2 + 1 = 3.
- (2, 1, 1): The value of 2*1 + 1 = 3.
Therefore, the total count of such triplets is 3.
Input: N = 5
Approach: The given problem can be solved by rearranging the equation A * B + C = N as A * B = N – C. Now, the only possible values A and B can have to satisfy the above equation is the divisors of N – C. For Example, if the value of N – C = 18, having 6 divisors that are 1, 2, 3, 6, 9, 18. So, values of A, B satisfying the above equation are: (1, 18), (2, 9), (3, 6), (6, 3), (9, 2), (18, 1). So, for the value of N – C = 18, possible values of A, B are 6, i.e., the number of divisors of N – C(= 18). Follow the steps below to solve the given problem:
- Initialize a variable, say count as 0 that stores the total count of possible triplets.
- Iterate a loop over the range [1, N – 1] using the variable i and for each value, i find the total count of divisors of (N – i) and add it to the variable count.
- After completing the above steps, print the value of count as the resultant number of triplets.
Below is the implementation of the above approach:
Time Complexity: O(N*sqrt(N))
Auxiliary Space: O(1)