শনিবার, ১২ ডিসেম্বর, ২০১৫

A mod B in O(number_of_digit_in(A))

Lets say you have a Big Integer A and an integer B . You want to calculate A mod B in O(length_of_(A)) time complexity . How to do that?

Lets say : A = 1234 (Not that big :-P ) and B = 6

I want to calculate 1234 % 6 . Now ,

s1 = 1234 % 6  =  ((123%6)*10 + 4)%6
                 =   (s2*10 + 4) %6  [If I know s2 I can calculate 1234 % 6 in O(1) now]

s2 = (123%6)  =  ((12%6)*10 + 3)%6
                        =  (s3*10 + 3)%6   [If I know s3 I can calculate 1234 % 6 in O(1) now]

s3 = (12 % 6 ) =  ( (1%6)*10 + 2)%6
                        =      ( s4*10 + 2) % 6 [If I know s4 I can calculate 1234 % 6 in O(1)  and s4 can be calculated in O(1)]


Now, We can easily implement this with a single loop which runs in O(n) . where,length(A) = n

So,



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//A is taken as string
//mod = B

int AmodB = 0;

for(int a=0;a<s.length();a++)
{
    AmodB = (AmodB*10 + (int)(s[a] - '0'))%mod;
    
} 

AmodB is initially (0*10 + 1)%6 = 1 (s4)
then,                       (1*10 + 2)%6 = 0 (s3)
then,                       (0*10 + 3)%6 = 3 (s2)
and finally,             (3*10 + 4)%6 = 4  (s1)

Theory : For any X , (X*k + m)%d = ((k%d)*X + m)%d

as, k can be written as a (multiple of d + remainder) this way  k = a*d + k%d ,for some integer a.
now, (X*k + m)%d

   =   (X*(a*d + k%d) + m)%d
   =   (X*a*d + X*k%d + m)%d
   =   (k%d*X + m)%d  [as,X*a*d % d = 0]

Now,put X = 10



Another approach : (1234)%6 = (4 + 3*10 + 2*100 + 1*1000)%6


so, ans =  (sigma(i = 0 to n-1)  (10^i*digit[i])%mod
The problem is how can I calculate (10^i%mod) efficiently and avoiding overflow?

Look, 10^5%mod = ((10^4)%mod*(10%mod))%mod
So,we can just save 10^(i-1)%mod in the loop and in the i'th iteration I'll find 10^i%mod by multiplying 10^(i-1)%mod [which I have already saved] and 10%mod [I can also save this into a variable to avoid repeated calculation] and "mod"ing the multiplied result.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
int mod_loop = 1;
int tmp = 0;
int ten_mod = 10%mod; //saving this
for(int a=s.length()-1;a>=0;a--)
{
    
    tmp+=(mod_loop*(int)(s[a] - '0' ) )%mod;

    
    mod_loop =((mod_loop)*ten_mod)%mod;


}

int ans = tmp%mod



Problems : Type 1) You'd need to mod a Big Integer very fast / You'd need to check divisibility (if B divides A) avoiding overflow and in O(length(A))

Type 2) You'll be given B and you have to find A such that B divides A and digits of A has a certain pattern such as A = 1111111........  , 12121212121212.................

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন