Finding k-th digit of a really large number

170 Views Asked by At

I am given 4 inputs, A, B, N and K where $-1 \lt A - \sqrt{B} \lt 1$. From that, I need to calculate the number $X^N$ so that $X = A + \sqrt{B}$ and print the K-th digit from that number. The problem is, the number is humongous, the range of the input is $1 \le A, B \le 10^4$, $1 \le N \le 10^9$ and $1 \le K \le 4$. The regular exponentiation in python returns an OverflowError so I tried implementing it by myself but still I get a NaN somewhere since the number is so big. Here is the code I used:

from sys import stdin, stdout
from math import sqrt


def exp(x, n):
    if n == 0:
        return 1
    k = x
    x = exp(x, int(n/2))
    x *= x
    if n%2 == 1:
        x *= k
    return x

A, B, N, K = [int(i) for i in stdin.readline().split()]

X = (A + sqrt(B))
X = exp(X, N)

k_th = int((X%(10**K))/(10**(K-1)))
stdout.write("%d\n" % k_th)

Is there an algorithm that can solve this type of problems? I thought on modular exponentiation but since $X$ is a real number and not an integer it didn't work.

You can see more details of this problem here. One thing I was pointed out was that since:

$$-1 \lt A - \sqrt{B} \lt 1$$ $$-1(A + \sqrt{B}) \lt A^2 + B \lt A + \sqrt{B}$$ $$-X \lt A^2 + B \lt X$$

and since $A$ and $B$ are both positive integers, $A + \sqrt{B} \gt 0$

Clarifications

A, B, N and K are integers

I need the k-th least significant digit in decimal base of $\lfloor X^N \rfloor$