Closest Numbers

  • + 0 comments

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger;

    public class Solution {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
    
        // Read number of test cases
        int T = Integer.parseInt(br.readLine().trim());
    
        // Process each test case
        for (int t = 0; t < T; t++) {
            String[] input = br.readLine().trim().split("\\s+");
            int a = Integer.parseInt(input[0]);
            int b = Integer.parseInt(input[1]);
            int x = Integer.parseInt(input[2]);
    
            // Calculate a^b using BigInteger for arbitrary precision
            BigInteger ab = power(a, b);
    
            // Find closest multiple of x to ab
            BigInteger closestMultiple = findClosestMultiple(ab, x);
    
            // Append result to StringBuilder
            sb.append(closestMultiple).append("\n");
        }
    
        // Print all results
        System.out.print(sb);
    }
    
    // Function to calculate a^b using BigInteger for arbitrary precision
    private static BigInteger power(int a, int b) {
        BigInteger result = BigInteger.ONE;
        BigInteger base = BigInteger.valueOf(a);
        BigInteger exponent = BigInteger.valueOf(b);
    
        while (exponent.compareTo(BigInteger.ZERO) > 0) {
            if (exponent.testBit(0)) { // If exponent is odd
                result = result.multiply(base);
            }
            base = base.multiply(base);
            exponent = exponent.shiftRight(1); // Divide exponent by 2
        }
    
        return result;
    }
    
    // Function to find closest multiple of x to num using BigInteger
    private static BigInteger findClosestMultiple(BigInteger num, int x) {
        BigInteger quotient = num.divide(BigInteger.valueOf(x));
        BigInteger closestSmaller = quotient.multiply(BigInteger.valueOf(x));
        BigInteger closestLarger = closestSmaller.add(BigInteger.valueOf(x));
    
        // Determine closest multiple
        if (num.subtract(closestSmaller).compareTo(closestLarger.subtract(num)) <= 0) {
            return closestSmaller;
        } else {
            return closestLarger;
        }
    }
    

    }