Greatest Common Divisor (GCD) of Big Numbers – A Recursive Approach (C++)

In this post I will provide mathematical background and C++ implementation of greatest common divisor (GCD) calculation of big numbers problem. Problem can be described as:

You have two numbers to calculate their GCD. First number is very big, let say 250 digits long. Other number is not so long, maybe less than 6 digits. How  do you calculate GCD of these two numbers. Continue reading

Merge Sort

Merge sort is a divide and conquer based algorithm. Its merge behavior names the algorithm. Algorithm details can be found elsewhere but I’ll give my basic merge-sort implementation here. It starts with dividing the array into two equal sized arrays. Division done until each array only holds an element. But merging procedure is the interesting part of the merge array. It merges 2 arrays into one sorted array. Continue reading

Finding The Half Of Linked List in Single Traversal

This is like a puzzle question: you iterate the list but at the end of the iteration (i.e. when you reach the end of linked list) you should display the half. The question seams hard because you do not know how many node exist in the list. So, how you find the half when you reach at the tail. One solution may be to store all elements into an array, but this is quite inefficient and possibly infeasible way to solve this question.

My proposed solution is:

  • Traverse the list with double next, this is iterating the list with node->next->next
  • Hold another pointer for half of the list. While iterating double next half of the list pointer iterates with one next.

I added the code for a simple list (supports addition to head, and tail – I did not test the tail :). Continue reading