Hackerrank Weekly #5 / problem 2

Tuesday problem is really easy. The full problem statement is here. You are given 3 integers a, b, x. You have to return the closest multiplicity of x to a^b. It's guaranteed that a^b \leq 10^9 which is really good. You have to do it fast, because one test file contains up to 10^5 testcases.

A pretty straightforward method for solving this is to first compute:

p := a^b

and two multiplicities of x:

1. The first one is the greatest number of form x \cdot k which is less or equal p, let's call it m_1:

m_1 := \lfloor p / x \rfloor \cdot x

2. The second one is the smallest number of form x \cdot k which is greater than p, let's call it m_2:

m_2 := (\lfloor p / x \rfloor + 1) \cdot x

It remains to return the closest one to p of these two numbers. Really easy task.