C++ Practice Problem – Collatz Conjecture

Time Limit: 2s Memory Limit: 192MB

Problem Description

Collatz Conjecture:

A Japanese middle school student discovered a fascinating “theorem” and asked Professor Kakutani to prove it, but the professor was unable to do so, leading to the Collatz conjecture. The conjecture states that for any natural number, if it is even, divide it by 2; if it is odd, multiply it by 3 and add 1. After obtaining a new natural number, continue to apply the above rules, and after several iterations, the result will inevitably be 1. Please write a program to verify this.

Input Format

Any positive integer

Output Format

The process of calculation

Sample Input

10

Sample Output

10/2=5

5*3+1=16

16/2=8

8/2=4

4/2=2

2/2=1

Code

#include <iostream>
using namespace std;
void jiaogu(int n) {
    while (n != 1) {
        if (n % 2 == 0) {
            cout << n << "/2=" << n/2 << endl;
            n = n / 2;
        } else {
            cout << n << "*3+1=" << n*3+1 << endl;
            n = n * 3 + 1;
        }
    }
}
int main() {
    int n;
    cin >> n;
    jiaogu(n);
    return 0;
}

Output ResultC++ Practice Problem - Collatz Conjecture

Methodology

  1. Read Input: Obtain a positive integer.

  2. Loop Calculation: Perform calculations based on the parity of the current number:

  • If it is even: n = n / 2

  • If it is odd: n = n * 3 + 1

  • Output Process: Output the calculation process after each operation.

  • Termination Condition: Stop when the result is 1.

  • Code Explanation

    1. Function<span>jiaogu</span>:

    • Even: Output<span>n/2=Result</span>, then divide n by 2

    • Odd: Output<span>n*3+1=Result</span>, then multiply n by 3 and add 1

    • Use a while loop, stopping when n equals 1

    • Determine the parity of n:

  • Main Function:

    • Read the input positive integer n

    • Call<span>jiaogu</span> function to perform calculations and output the process

    C++ Practice Problem - Collatz Conjecture

    C++ Basic Tutorial Collection

    C++ Practice Problem - Collatz ConjectureC++ Basic Materials

    1. C++ Output

    2. C++ Variables

    3. C++ Input

    4. C++ Expressions

    5. IF Statements

    6. IF Applications

    7. WHILE Loop Statements

    8. FOR Loop Statements

    9. Arrays

    10. One-Dimensional Arrays

    11. Two-Dimensional Arrays

    12. C++ Functions

    13. C++ File Operations – Writing Files

    If you find it interesting, please click on me

    C++ Practice Problem - Collatz ConjectureC++ Practice Problem - Collatz ConjectureC++ Practice Problem - Collatz ConjectureC++ Practice Problem - Collatz Conjecture

    Leave a Comment