Given an infinite stream of bits with bits being appended at the highest significant position. Give an algorithm to say whether the number formed by sequence of bits that had been processed till then is divisible by 3 or not ?
Solution from Algogeeks group :
Divisibility of 3 of numbers in base 2 can be seen same as divisibility of numbers by 11 in base 10.
Maintain two variable even_sum & odd_sum, both initialized to 0.When an odd location in the number is set increment odd_sum.When an even location in the number is set increment even_sum.
if(abs(even_sum-odd_sum)%3==0) number is divisible by 3.
Hence keep the track of even_sum and odd_sum as the bits are getting appended.
Number of bits set in odd position - Number of bits set in even position 'll be divisible by 3
For example, take 9. 1001. No. of bits set in odd position-number of bits set in even position is 0.Hence divisible by 3.
For 21, 10101. Difference is 3.. SO just keep count of the number of bits set in odd position and even position as the stream.
If the stream contains numbers :
For calculating the sum, no need to store all the elements sum.After adding a number each time,take modulus and store the remainder in sum.So it will not become more and will be less than 3.
No comments:
Post a Comment