C/C++ and Python Program to find GCD of a list of numbers




A very easy question though, yet thought posting about it thinking it may improve my explanation prowess.

Lets get back to old school math, how did we find Greatest Common Divisor (GCD) or you may call it Highest Common Factor(HCF) of two numbers?

Assuming you know primary Maths, I'd proceed further.

Lets take an example before we go ahead.

Find GCD of 54 and 24.

Divisors of 54 are: 1, 2, 3, 6, 9, 18, 27, 54.

Divisors of 24 are: 1, 2, 3, 4, 6, 8, 12, 24.

Common divisors of 54 and 24: 1, 2, 3, 6

The greatest of these is 6.

Hence gcd(54,24) = 6

Okay, lets write an algorithm for this. Well, one would say, there's nothing to think of any algorithm, things are crystal clear. Find out the factors of two numbers, then find common factors and then the largest of them.

But brother! There exists a better algorithm. Our Father of Geometry, Euclid, left us an algorithm already. We simply have to implement it.

Fast Power Algorithm: C/C++ and Python Code




In competitive programming, traditional way to finding power may not work sometimes.

By traditional way I mean if we have to find 2^10 (just as an example).

Or else simply by using library function after including math.h (in C) we can do it by pow(2,10)

Well, but this doesn't help us anymore when it comes to finding base to the power (base^power) where power could be anything in the range 0 to 1000000 or even greater value, same goes for base

Whilst you may think it impractical but in competitive programming questions ask us find Modulus of the answer by any prime number such as 1000000007, just to make sure answer remains in range of int data type.

i.e. pow(2,100)%1000000007 = 976371285

Lets come to the point and discuss what you have come for :)

Fast Algorithm:

result = 1
If power is odd:
    result = result*value

value = value*value
power = power/2


Yeah, I know, above algorithm more looks like a code & was nothing but a bouncer. ;)