Monday 12 June 2017

Get the modulo of a very large number that cannot be stored in any data type in C/C++!

Today we will solve problem of finding modulo of huge numbers.

Lets see the modulo operation first:

It is a distributive over addition, multiplication. i.e.

(A+B)%m = (A%m + B%m) %m
(A*B)%m = (A%m * B%m) %m

These two will help here, mainly the first one.

Consider, 'abcdepqr' is a string of digits, ok?
Is not abcdepqr = (abcde*1000 + pqr) ? Yes, it is.

Similarly, (a*10000000 + bcdepqr), right?
This is the thing we are going to apply.

What will we do is,
Get one variable to store the answer initialized to zero.

Scan the string from left to right,

Everytime multiply the answer by 10 and add the next number and take the modulo and store this as new answer.

E.g. 12345 % 100:
ans = 0
ans = (o*10 + 1)%100
ans = (1*10 + 2)%100
ans = (12*10 + 3)%100
ans = (23*10 + 4)%100
ans = (34*10 + 5)%100
ans = 45.

It means: we, at the end, are doing this only:
a*10000000 + b*1000000 + c*100000 + d*10000 + e*1000 + p*100 + q*10 + r
which is nothing but 'abcdepqr'!

This way have proved the correctness too.

Reference: https://www.hackerearth.com/practice/notes/get-the-modulo-of-a-very-large-number-that-cannot-be-stored-in-any-data-type-in-cc-1/

Monday 17 April 2017

An intelligent trader carries 3 sacks having 30 coconuts each. On the way he passes through 30 checkpoints. On every checkpoint he has to give one coconut each from each sack. How many coconuts does he have left?

Note: Initially,  it will look you quite simple and you think it is zero.
But here you have to emphasise on the word An intelligent trader, so you need to think according to an intelligent trader.
Being an intelligent trader he will definitely use all his intelligence to get the profit that is by trying to safe as much coconut as possible so
3 sacks each having 30 coconut total= 90 coconuts.
Now 30 check point and at each checkpoint he has to give coconut as much he have number of sack so, for the first 10 checkpoint he will use only one sack and give 30 coconuts.
Now he left with 2 sacks and 20 check points.
So for next 15 checkpoint he will use another sack and give coconuts from it.
After this he is left with 1 sack and 5 check points so by giving one at each point he will left with 25 coconuts.
So finally 25 coconut is left.