VOOZH about

URL: https://www.geeksforgeeks.org/dsa/highest-power-of-a-number-that-divides-other-number-set-2/

⇱ Highest power of a number that divides other number | Set - 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Highest power of a number that divides other number | Set - 2

Last Updated : 23 Jul, 2025

Given two numbers N and M(M > 1), the task is to find the highest power of M that divides N. 

Examples:

Input: N = 12, M = 2
Output: 2
Explanation: The powers of 2 which divide 12 are 1 and 2 (21 = 2 and 22 = 4 which both divide 12). 
The higher power is 2, hence consider 2.

Input: N = 500, M = 5
Output: 3.

Naive and Bit Manipulation Approach:  The naive approach and bit manipulation approach is already mentioned in the Set 1 of this problem.

Efficient Approach: The task can be solved using a binary search technique over the range [1, logB(A)]. For each value x in the range, check if Mx divides N. Finally, return the largest value possible

Follow the below steps to solve the problem:

  • Find the value of logM(N)
  • Run binary search in range [1, logM(N)] .
  • For each value x, check if Mx divides N, and find the largest such value possible.

Below is the implementation of the above approach.

 
 


Output
2

Time Complexity: O(log(logM(N)))
Auxiliary Space: O(1) 

Comment