Closest Number

Published on August 06, 2021
Last updated August 06, 2021

Problem description

You are given 3 numbers a, b and x. You need to output the multiple of x which is closest to pow(a,b). If more than one answer exists , display the smallest one.

Input Format

The first line contains T, the number of testcases.
T lines follow, each line contains 3 space separated integers (a, b and x respectively)


1 ≤ T ≤ pow(10,5) 1 ≤ x ≤ pow(10,9) 0 < pow(a,b) ≤ pow(10,9) 1 ≤ a ≤ pow(10,9) pow(-10,9) ≤ b ≤ pow(10,9)

Output Format

For each test case,output the multiple of x which is closest to power(a,b)


if the pow(a,b) modules x is greater than half of x the closest number would be x - pow(a,b) modules x greater than that of the pow(a,b).

If pow(a,b) modules x is not greater than half of x then the closest number would be pow(a,b) modules x less than pow(a,b).

Link to the problem on hackerrank

Solution in java

import java.util.*;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        int num_of_test_cases = sc.nextInt();
        while (num_of_test_cases > 0) {
            long a = sc.nextInt();
            long b = sc.nextInt();
            long x = sc.nextInt();
            long apowb = (long) Math.pow(a, b);
            if (apowb % x > x / 2)
                System.out.println(apowb + x - apowb % x);
                System.out.println(apowb - apowb % x);

Tags :