Start free

Expert · Number theory · 243 of 264

Any base to any base

Convert a number between bases 2 and 36. Digits above 9 are the capital letters A to Z. Do not use int(x, base) or similar built-ins for the conversion.

Input: the number, its base, and the target base, one per line. Output: the number in the target base.

Examples

Input
255
10
16
Output
FF
Input
FF
16
2
Output
11111111
Input
0
8
3
Output
0

2 more tests check other inputs when you press Check.

Stuck? The idea behind number theory

Whole-number tricks: n % d == 0 means d divides n; test divisors only up to the square root; the sieve of Eratosthenes finds every prime up to n at once.

pow(a, b, m) works out a to the power b, modulo m, quickly, even when the power is huge.

n = 50
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
    if is_prime[i]:
        for j in range(i * i, n + 1, i):
            is_prime[j] = False
print(sum(is_prime))

Watch for: Testing every number up to n one by one is too slow for big inputs: the hidden tests notice.

All the number theory exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More number theory exercises