C++: Collatz Conjecture Program

The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. Otherwise, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. [wikipedia]


 a_n={1/2a_(n-1)   for a_(n-1) even; 3a_(n-1)+1   for a_(n-1) odd
Image source : wolfram
     
                    
C++ implementation of Collatz conjecture


#include <iostream>
#include <cassert> //assert()
int main()
{
    int n;
    std::cout << "Enter number (greater than 1)\n";
    std::cin >> n;
    assert(n > 1);
    std::cout << "Series is :\n";
    std::cout << n << " ";
    while(n != 1)
    {
        if (n % 2 == 0)
        {
            n = n / 2;
            std::cout << n << " ";
        }
        else
        {
            n = (3 * n) + 1;
            std::cout  << n << " ";
        }
    }
    std::cout << '\n';
}
 
You can view this code on GitHub.
Collatz Conjecture





                                                                  
                                                                  
Reference:
 

You may also like 

C++: Find Prime Factors of a Number
C++: Tic Tac Toe
C++: Bellman Ford Algorithm using STL
C++: Add binary numbers
C++: Remove all adjacent duplicates from String using Stack

Comments