Challenge: Closest Number

Subdomeniu: Number Theory (number-theory)

Scor cont: 30.0 / 30

Submission status: Accepted

Submission score: 1.0

Submission ID: 464725126

Limbaj: python3

Link challenge: https://www.hackerrank.com/challenges/closest-number/problem

Cerinta

You are given 3 numbers *a*, *b* and *x*. You need to output the multiple of *x* which is closest to *a<sup>b</sup>*. 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)

Output Format

For each test case , output the multiple of *x* which is closest to *a<sup>b</sup>*

Constraints

1 ≤ *T* ≤ 10<sup>5</sup>  
1 ≤ *x* ≤ 10<sup>9</sup>  
0 < *a<sup>b</sup>* ≤ 10<sup>9</sup>    
1 ≤ *a* ≤ 10<sup>9</sup>    
-10<sup>9</sup> ≤ *b* ≤ 10<sup>9</sup>

Cod sursa

#!/bin/python3

import math
import os
import random
import re
import sys

def closestNumber(a, b, x):
    f=(math.floor((a**b)/x)*x)
    c=(math.ceil((a**b)/x)*x)
    if((a**b)-f<c-(a**b)):
        return f
    return c
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        first_multiple_input = input().rstrip().split()

        a = int(first_multiple_input[0])

        b = int(first_multiple_input[1])

        x = int(first_multiple_input[2])

        result = closestNumber(a, b, x)

        fptr.write(str(result) + '\n')

    fptr.close()
HackerRank Number Theory – Closest Number