Member-only story
In C++, write a method that follows the Collatz conjecture. If n is even set n=n/2 and if n is odd set n=3n+1.
Question
The Collatz conjecture states that when taking any natural number n, if n is even, set n = n /2. If n is odd, set n = 3n + 1. Repeat this process until n is equal to 1. The conjecture states that no matter what number you start with, you will always reach 1.
Explanation
Create a while loop where it will exit out of the loop once n is equal to 1. It will keep iterating in the loop as long as n is NOT equal to 1. Within the while loop, if n%2 which translates to if n divided by 2 has a remainder of 1, then divide the n by 2. Else, if there is no remainder when n is divided by 2, then n=3n+1.
Whenever the while loops make a successful iteration, then increase the counter named ‘count’ by 1. After the while loop exits, then print out the counter ‘count’ which is the total number of iterations the while loop has gone through. The variable ’n’ should be 1 when it exits the while loop.
Solution
int main(){int n,count;while(cin >> n && n) {count = 0;while( n != 1 ) {if(n%2 == 0) n = n/2;else n = 3*n + 1;count++;}cout << "There are " << count;cout << " numbers being generated!" << endl;}}