Given two positive integers P and Q, the task is to largest divisor of P which is not divisible by Q.
Input: P = 10, Q = 4
Explanation: 10 is the largest number which divides 10 but not divisible by 4.
Input: P = 12, Q = 6
Explanation: 4 is the largest number which divides 12 but not divisible by 6.
Approach: The simplest approach is to find all the divisors of P and obtain the greatest of these divisors, which is not divisible by Q.
Time Complexity: O(√P)
Auxiliary Space: O(1)
Alternate Approach: Follow the steps below to solve the problem:
- Store the count of frequencies of prime factors of Q in a HashMap divisors.
- Initialize a variable, say ans, to store the greatest number X, such that X divides P but is not divisible by Q.
- Iterate through all divisors of Q and perform the following steps:
- Store the count of frequencies of the current prime divisor in a variable, say frequency.
- Store the count of frequencies of the current prime divisor on dividing P in a variable, say cur, and initialize num as the current prime divisor * (frequency – cur + 1).
- If the value of cur is less than frequency, then update the variable ans to P and break out of the loop.
- Otherwise, divide P with num and store the result in a variable, say tempAns.
- After completing the above steps, update the value of ans to the maximum of ans and tempAns.
- After completing the above steps, print the value of ans as the maximum possible result.
Below is the implementation of the above approach:
Time Complexity: O(sqrt(Q) + log(P) * log(Q))
Auxiliary Space: O(Q)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.