fork(2) download
  1. #include <iostream>
  2. #include <cstdint>
  3. #include <limits>
  4.  
  5. int main()
  6. {
  7. constexpr std::size_t NPEGS = 3U ;
  8. const char peg[NPEGS] = { 'A', 'B', 'C' } ;
  9. constexpr std::size_t MAX = std::numeric_limits<std::uintmax_t>::digits ;
  10.  
  11. std::size_t ndisks ;
  12. std::cout << "ndisks ( 1 - " << MAX << ")? " ;
  13. std::cin >> ndisks ;
  14.  
  15. if( ndisks > 0 && ndisks < MAX )
  16. {
  17. const std::uintmax_t num_moves = ( 1U << ndisks ) - 1 ; // 2^n - 1
  18. std::cout << ndisks << " disks, " << num_moves << " moves\n" ;
  19.  
  20. // see: http://e...content-available-to-author-only...a.org/wiki/Tower_of_Hanoi#Binary_solution
  21. for( std::uintmax_t nmove = 1 ; nmove <= num_moves ; ++nmove )
  22. {
  23. const auto from = ( nmove & (nmove-1) ) % NPEGS ;
  24. const auto to = ( ( nmove | (nmove-1) ) + 1 ) % NPEGS ;
  25. std::cout << nmove << ". from " << peg[from] << " to " << peg[to] << '\n' ;
  26. }
  27. }
  28. }
  29.  
Success #stdin #stdout 0s 3344KB
stdin
5
stdout
ndisks ( 1 - 64)? 5 disks, 31 moves
1. from A to C
2. from A to B
3. from C to B
4. from A to C
5. from B to A
6. from B to C
7. from A to C
8. from A to B
9. from C to B
10. from C to A
11. from B to A
12. from C to B
13. from A to C
14. from A to B
15. from C to B
16. from A to C
17. from B to A
18. from B to C
19. from A to C
20. from B to A
21. from C to B
22. from C to A
23. from B to A
24. from B to C
25. from A to C
26. from A to B
27. from C to B
28. from A to C
29. from B to A
30. from B to C
31. from A to C