#include // This program prints the sequence of values in the // '3n + 1' problem, also known as the Collatz problem. // // Starting with a positive integer 'n', after printing // the current value, the next value is // // n/2 if 'n' is even, and // 3*n + 1 if 'n' is odd. // // For example, starting with 6 produces // // 6, 3, 10, 5, 16, 8, 4, 2, 1. // // It is conjectured that every positive starting // integer will eventually reach 1. Once 1 is reached, // continuing the process produces the cycle // // 1, 4, 2, 1, 4, 2, 1, ... // // Despite its simple statement, no proof is known // that every positive integer eventually reaches 1. // // Exercises: // // 1. Modify the program so that the user must enter // an integer greater than or equal to 1. If the // user enters a smaller value, repeatedly query // the user until a valid value is entered. // // 2. Add a counter that records the number of // iterations required to reach 1. // // For example, if the user enters 42, the output // should be // // 42, 21, 64, 32, 16, 8, 4, 2, 1 // Iterations: 8 // // Notice that the starting value is not itself // an iteration. Each change from one value to the // next counts as one iteration. // // 3. Modify the output so that there is no trailing // comma after the final value 1. // Function declarations int main(); // Function definitions int main() { int n{}; std::cout << "Enter a positive integer: "; std::cin >> n; while ( n != 1 ) { std::cout << n << ", "; if ( n%2 == 0 ) { n /= 2; } else { n = 3*n + 1; } } std::cout << 1 << std::endl; return 0; } // Hint for Exercise 1: // // Use a loop that repeatedly queries the user until // the condition // // n >= 1 // // is satisfied. // Hint for Exercise 2: // // Each time the program changes 'n' to the next // value in the sequence, one iteration has occurred. // // Create a counter before the loop and increment it // once during each iteration of the loop. // Hint for Exercise 3: // // The existing program already avoids a trailing // comma by printing each value followed by ", " // only while n != 1. // // The final value 1 is then printed separately. // Here is one solution: /* int main() { int n{}; while ( true ) { std::cout << "Enter a positive integer: "; std::cin >> n; if ( n >= 1 ) { break; } } int iterations{ 0 }; while ( n != 1 ) { std::cout << n << ", "; if ( n%2 == 0 ) { n /= 2; } else { n = 3*n + 1; } ++iterations; } std::cout << 1 << std::endl; std::cout << "Iterations: " << iterations << std::endl; return 0; } */