We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.math.BigInteger;publicclassSolution{publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));StringBuildersb=newStringBuilder();// Read number of test casesintT=Integer.parseInt(br.readLine().trim());// Process each test casefor(intt=0;t<T;t++){String[]input=br.readLine().trim().split("\\s+");inta=Integer.parseInt(input[0]);intb=Integer.parseInt(input[1]);intx=Integer.parseInt(input[2]);// Calculate a^b using BigInteger for arbitrary precisionBigIntegerab=power(a,b);// Find closest multiple of x to abBigIntegerclosestMultiple=findClosestMultiple(ab,x);// Append result to StringBuildersb.append(closestMultiple).append("\n");}// Print all resultsSystem.out.print(sb);}// Function to calculate a^b using BigInteger for arbitrary precisionprivatestaticBigIntegerpower(inta,intb){BigIntegerresult=BigInteger.ONE;BigIntegerbase=BigInteger.valueOf(a);BigIntegerexponent=BigInteger.valueOf(b);while(exponent.compareTo(BigInteger.ZERO)>0){if(exponent.testBit(0)){// If exponent is oddresult=result.multiply(base);}base=base.multiply(base);exponent=exponent.shiftRight(1);// Divide exponent by 2}returnresult;}// Function to find closest multiple of x to num using BigIntegerprivatestaticBigIntegerfindClosestMultiple(BigIntegernum,intx){BigIntegerquotient=num.divide(BigInteger.valueOf(x));BigIntegerclosestSmaller=quotient.multiply(BigInteger.valueOf(x));BigIntegerclosestLarger=closestSmaller.add(BigInteger.valueOf(x));// Determine closest multipleif(num.subtract(closestSmaller).compareTo(closestLarger.subtract(num))<=0){returnclosestSmaller;}else{returnclosestLarger;}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Number
You are viewing a single comment's thread. Return to all comments →