Javatpoint Logo
Javatpoint Logo

Tower of Hanoi Algorithm in C++

Introduction to Mathematical Puzzles in Coding

Mathematical puzzles in coding combine the power of mathematics and logic to create engaging challenges that test problem-solving skills and algorithmic thinking. These puzzles often serve as captivating exercises for both seasoned programmers and beginners, offering a delightful way to hone their coding abilities while exploring the elegance of mathematical concepts. In this introduction, we will delve into the fascinating world of mathematical puzzles in coding, exploring their significance, types, and the benefits they offer to aspiring programmers.

Significance of Mathematical Puzzles in Coding

Mathematical puzzles form an essential part of the coding universe due to their ability to stimulate critical thinking and creativity. They offer a refreshing approach to programming, fostering a deeper understanding of algorithms and data structures. These puzzles transcend the mundane coding exercises, infusing intrigue and excitement into the learning process. As programmers tackle these challenges, they unlock new problem-solving techniques and gain exposure to advanced mathematical principles, reinforcing the crucial connection between mathematics and computer science.

Types of Mathematical Puzzles in Coding

There exists a rich variety of mathematical puzzles in coding, each with its unique set of rules and problem domains. One of the most renowned examples is the "Tower of Hanoi," a classic puzzle that demands recursive thinking to transfer disks between pegs while adhering to specific constraints. Additionally, "Sudoku" puzzles, which involve filling a 9x9 grid with digits based on certain rules, test the implementation of backtracking algorithms and logical deduction skills. "Knapsack problems" challenge programmers to find the optimal way of packing items into a container with limited capacity, effectively incorporating dynamic programming concepts. Furthermore, "Fibonacci sequences" and "Prime number generators" exemplify how mathematical concepts are utilized to craft coding challenges that unravel the beauty of number theory and sequence generation.

Benefits of Solving Mathematical Puzzles in Coding

Solving mathematical puzzles in coding provides a plethora of advantages to programmers of all levels. Firstly, it nurtures problem-solving and analytical skills, teaching programmers to approach complex challenges with a systematic mindset. Secondly, it fosters creativity, encouraging programmers to think outside the box and devise innovative solutions. Thirdly, tackling these puzzles enhances algorithmic efficiency, as programmers seek optimized ways to solve problems using minimal computational resources. Moreover, it strengthens their grasp of mathematical principles, promoting a well-rounded understanding of computer science concepts. Finally, the joy of successfully overcoming mathematical puzzles instills a sense of accomplishment and motivation, driving programmers to explore further and embrace coding as a rewarding and intellectually stimulating pursuit.

In conclusion, mathematical puzzles in coding serve as a gateway to an enchanting realm where mathematics and programming intertwine. As programmers immerse themselves in the intricacies of these challenges, they embark on a journey of discovery, honing their skills and unraveling the beauty of both mathematics and coding. With an array of puzzles awaiting exploration, these captivating exercises promise endless opportunities for growth, making the experience of coding both intellectually enriching and deeply gratifying.


The history of mathematical puzzles in coding can be traced back to ancient civilizations, where early mathematicians and scholars engaged in various intellectual games and challenges. The concept of mathematical puzzles has evolved over centuries, influenced by cultural exchange and technological advancements.

One of the earliest recorded mathematical puzzles is the "Babylonian Square Puzzle," found on a clay tablet dating back to around 1800 BCE. This puzzle involved finding the dimensions of a square given its area, exemplifying the ancient Babylonians' interest in mathematical problem-solving.

In medieval times, the Islamic Golden Age saw significant contributions to mathematics and puzzle-solving. Scholars like Al-Khwarizmi and Omar Khayyam made substantial advancements in algebra and geometry, which laid the foundation for more complex mathematical puzzles.

During the Renaissance, mathematicians such as Leonardo da Vinci and Leonhard Euler contributed to the development of mathematical puzzles and recreational mathematics. Euler, in particular, is famous for his work on graph theory, which gave rise to the concept of the "Seven Bridges of Königsberg" problem.

In the 20th century, the advent of computers and programming languages opened up new possibilities for mathematical puzzles in coding. Early computer scientists, like Alan Turing, tackled puzzles related to computation and decision problems, which laid the groundwork for modern algorithms and coding challenges.

With the proliferation of the internet and online communities, mathematical puzzles in coding have become popular among programmers of all levels. Coding platforms and websites offer a vast array of challenges, encouraging enthusiasts to explore and solve problems rooted in mathematics and logic.

In conclusion, the history of mathematical puzzles in coding reflects the continuous exploration of human intellect, from ancient civilizations to the modern digital era. These puzzles have not only entertained and engaged generations but also played a significant role in advancing mathematics and computer science, making them an integral part of the ever-evolving world of coding.

The Tower of Hanoi problem is a classic mathematical puzzle that consists of the following setup:

You are given three pegs (or rods) labeled A, B, and C. On peg A, there is a stack of n disks, each of a different size, arranged in increasing order of their size from top to bottom. The goal of the puzzle is to move all the disks from peg A to peg C, using peg B as an auxiliary, following three simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the top disk from one peg and placing it on top of another peg (either an empty peg or a larger disk).
  • No larger disk can be placed on top of a smaller disk.

The Tower of Hanoi problem has a recursive solution, and the challenge is to find the minimum number of moves required to transfer the entire stack of disks from peg A to peg C while adhering to the rules.

The Tower of Hanoi puzzle is not just a recreational problem; it has real-world applications in computer algorithms, recursion, and problem-solving strategies. It also serves as a fundamental example in teaching the concepts of recursion and algorithm design.


Algorithm for tower of Hanoi:

Follow the steps below to solve the problem:

  • Create a function towerOfHanoi where pass the N (current number of disk), from_rod, to_rod, aux_rod.
  • Make a function call for N - 1 th disk.
  • Then print the current the disk along with from_rod and to_rod
  • Again make a function call for N - 1 th disk.

Below is the program for the problem tower of hanoi in C++:


Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Process executed in 1.11 seconds
Press any key to continue


  1. #include <bits/stdc++.h>: This line includes a standard C++ library header that includes most of the standard headers like <iostream>, <vector>, <algorithm>, etc. It's a shortcut often used in competitive programming, but it's not considered good practice for regular C++ programs.
  2. using namespace std;: This line brings all the elements from the std (standard) namespace into the current scope, allowing the use of standard C++ functions and objects without prefixing them with std::.
  3. void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod): Declaration of a function named towerOfHanoi that takes four parameters - n is the number of disks, from_rod is the source rod, to_rod is the destination rod, and aux_rod is the auxiliary rod.
  4. if (n == 0) { return; }: This is the base case of the recursive function. If the number of disks is zero, the function returns without performing any further recursion.
  5. towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);: Recursively calls the towerOfHanoi function with n-1 disks, swapping the roles of to_rod and aux_rod in the parameters.
  6. cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl;: Prints a message indicating the move of a disk from one rod to another.
  7. towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);: Recursively calls the towerOfHanoi function with n-1 disks again, swapping the roles of from_rod and aux_rod in the parameters.
  8. int main(): The beginning of the main function.
  9. int N = 3;: Declares an integer variable N and initializes it with the value 3, representing the number of disks in the Tower of Hanoi problem.
  10. towerOfHanoi(N, 'A', 'C', 'B');: Calls the towerOfHanoi function with the initial parameters to solve the Tower of Hanoi problem for 3 disks, with rods named 'A', 'C', and 'B'.
  11. return 0;: Indicates successful execution of the program.

Time and Space Complexity Analysis

Time Complexity:

The time complexity of the Tower of Hanoi algorithm is often expressed using the recurrence relation. In this case, let T(n) be the time complexity for solving the Tower of Hanoi problem with n disks. The recurrence relation is given by:


Here, the algorithm makes two recursive calls to solve the problem with n-1 disks, and it also performs a constant number of operations (printing the move). The recurrence relation indicates that the time complexity is exponential, specifically O(2n). This is because each level of recursion doubles the work done, resulting in an exponential growth in the number of operations as the number of disks increases.

Space Complexity:

The space complexity is determined by the amount of memory used by the program, especially in terms of function call stack space during recursion. In this code, the primary use of memory comes from the function call stack, as each recursive call adds a new frame to the stack.

For the Tower of Hanoi problem, the maximum depth of the recursion is n, corresponding to the number of disks. Therefore, the space complexity of the algorithm is O(n), as it requires space proportional to the number of disks to keep track of the recursive calls.

It's important to note that the space complexity is linear with respect to the number of disks, making it more manageable than the time complexity. However, the time complexity remains exponential, making the algorithm less efficient for large numbers of disks. The Tower of Hanoi problem highlights the trade-off between time and space complexity in recursive algorithms, as the recursive nature simplifies the code but can result in exponential time complexity.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA