Given two positive integers n and k. Find minimum positive integer x such that the (x % k) * (x / k) == n, where % is the modulus operator and / is the integer division operator.
Input : n = 4, k = 6 Output :10 Explanation : (10 % 6) * (10 / 6) = (4) * (1) = 4 which is equal to n Input : n = 5, k = 5 Output : 26
Naive Solution : A simple approach is to run a while loop until we find a solution which satisfies the given equation, but this would be very slow.
Efficient Solution : The key idea here is to notice that the value of (x % k) lies in the range [1, k – 1]. (0 is not included, since we can’t divide n by (x % k) when it is zero). Now, we need to find the largest possible number in the range that divides n and hence the given equation becomes x = (n * k) / (x % k) + (x % k).
Note : (x % k) is added to the answer since for the current value of modulus (x % k), it must not be contradicting that on one hand x is such that the remainder upon dividing by k is (x % k) and on the other x is (n * k) / (x % k) whose remainder is simply zero when we divide this value by k.
Below is the implementation of the above approach.
Time Complexity : O(k), where k is the given positive integer.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find minimum x such that (x % k) * (x / k) == n | Set-2
- Find the value of N when F(N) = f(a)+f(b) where a+b is the minimum possible and a*b = N
- Find the minimum value of X for an expression
- Find triplet with minimum sum
- Find minimum possible values of A, B and C when two of the (A + B), (A + C) and (B + C) are given
- Find the node whose xor with x gives minimum value
- Find the subarray of size K with minimum XOR
- Find two numbers with the given LCM and minimum possible difference
- Find the node whose sum with X has minimum set bits
- Find minimum GCD of all pairs in an array
- Find minimum positive integer x such that a(x^2) + b(x) + c >= k
- Find minimum sum of factors of number
- Find the minimum permutation of A greater than B
- Find the minimum value of the given expression over all pairs of the array
- Find the minimum number possible by changing at most one digit
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.