# Find the multiple of x which is closest to a^b in C++

Suppose we have three integers, a, b and x. The task is to get the multiple of x, which is closest to ab. So if a = 5, b = 4 and x = 3, then output will be 624. As 54 = 625, and 624 is the multiple of 3, which is closest to 625.

The task is simple. we have to follow these steps to solve this problem −

• calculate num := ab
• Then find f := floor of (num/x)
• Now the closest element at the left will be cl = x * f, and at right will be cr = x * (f + 1)
• Finally, the closest number among them will be min(num – cl, cr – num)

## Example

Live Demo

#include <iostream>
#include <cmath>
using namespace std;
long long getClosest(int a, int b, int x) {
long long num = pow(a, b);
int f = floor(num / x);
long long cl = x * f;
long long cr = x * (f + 1);
if ((num - cl) < (cr - num))
return cl;
else
return cr;
}
int main() {
int a = 5, b = 4, x = 3;
cout << "Find closest element: " << getClosest(a, b, x);
}

## Output

Find closest element: 624