Find the multiple of x which is closest to a^b

Given three integers a, b and x, the task is to get the multiple of x which is closest to ab.


Input: a = 5, b = 4, x = 3
Output: 624
54 = 625 and 624 is the multiple of 3 which is closest to 625

Input: a = 349, b = 1, x = 4
Output: 348


  • Calculate ab and store it in a variable say num.
  • Then, calculate ⌊num / x⌋ and store it in a variable floor.
  • Now the closest element at the left will be closestLeft = x * floor.
  • And the closest element on the right will be closestRight = x * (floor + 1).
  • Finally, the closest number among them will be min(num – closestLeft, closestRight – num).

Below is the implementation of the above approach:






// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
// Function to return the multiple of x 
// which is closest to a^b
ll getClosest(int a, int b, int x)
    ll num = pow(a, b);
    int floor = num / x;
    // Closest element on the left
    ll numOnLeft = x * floor;
    // Closest element on the right
    ll numOnRight = x * (floor + 1);
    // If numOnLeft is closer than numOnRight
    if ((num - numOnLeft) < (numOnRight - num))
        return numOnLeft;
    // If numOnRight is the closest
        return numOnRight;
// Driver code
int main()
    int a = 349, b = 1, x = 4;
    cout << getClosest(a, b, x) << endl;
    return 0;





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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.

Improved By : jit_t