What is the best way to store large base B numbers so that the operations like right shift and checking the least significant bit can be done efficiently?
Actually, I have came across an interview question which says that
Given two numbers N and K such that 0<=N<=1000 and 0<=K<=1000^1000. I need
to check that whether N^N = K or not. For example:
if N=2 and K=4 , 2^2 = 4 so return true;
if N=3 and K=26 , 3^3 != 26 so return false
What I was thinking is that if I consider base N number system
, then N^N
will be equivalent to 1 followed by N zero
in it. For e.g - For N = 2, 2^2 = 100(in base 2), for N=3, 3^3 = 1000(in base 3). I can then easily write a function to tell whether K = N^N
or not.
int check(unsigned long int N, unsigned long int K)
{
unsigned long int i;
for (i=0; i<N; i++)
{
if (K%N != 0) //checking whether LSB is 0 or not in base N number system
return 0;
K = K/N; //right shift K by one.
}
return (K==1);
}
Now there are two major problems with this function:
1) An unsigned long int is not sufficient to store large numbers of range 0
to 1000^1000.
2) The modulus and the division operations makes it every less efficient.
In order to make it efficient, I am looking for some way to represent large base N numbers so that I can perform right shift and checking the least significant bit operations efficiently. Does anyone came across such thing before? Or anyone know any other way to solve this problem efficiently?