Monday 21 July 2014

New semester new story.

My 3rd semester is just about to start within a day from now.I'll try my best to make full use of time and the resources I have in this semester.
Just last night I participated in Codechef's Cook Off and did 2/5 problems . These two problems were very easy the other three were somewhat difficult out of those 3 two were touching the concepts of graph theory.
I made a wrong submission that costed me a penalty of 20 mins. otherwise I would have been in under 300 for sure but still I got 453 rank.

I got a method to calculate both LCM and HCF and that too very fast O(LogN). Yes,if you know it already I am talking about Euclid's GCD theorem.

Its like this -
Lets say we want to calculate GCD(Greatest Common Divisor or Highest Common Factor) of two given numbers lets say A,B .

So, pseudo code of the algorithm looks like this -
START-
GCD(A,B):
    if B>A return GCD(B,A)
    else:
        if A%B==0 return B
        else return GCD(B,A%B)
END
For example lets say A=12,B=18
calling GCD(12,18)
so as B>A it returns GCD(18,12)
then as 18%12=6 which is not equal to 0 it returns GCD(12,6)
but now as 12%6=0 it finally returns 6 . So, 6 is the GCD of 12,18

This method is very old yet very effective method to calculate the Highest Common Factor of given two numbers.

Now to calculate LCM all we need to do is just multiplay the no. A & B and divide the product with the GCD of A & B.
For example lets say A=12,B=18
So, LCM of 12,18 will be 12*18/GCD(12,18) = 12*18/6 = 36
Time Complexity of this algorithm is also O(LogN) as multiplication is O(1) and GCD is O(LogN)
So,Now we have two very effective algorithms to calculate HCF,LCM of two numbers .

Thanks for reading and Happy Coding :) .

No comments:

Post a Comment