Luogu brush questions C++ language | P5727 Hail conjecture

Learn C++ from a baby! Record the questions in the process of Luogu C++ learning and test preparation, and record every moment.

Attached is a summary post: Luogu Brush Questions C++ Language | Summary


【Description】

Given a positive integer  n , the following operation has been performed on this number: if the number is odd, then multiply it by 3 and add 1, otherwise divide by 2. After several cycles, it will eventually return to 1. It has been verified that very large numbers (7×10^11) can be compared to 1 in this way, so it is called "hail conjecture". For example, when  n  is 20, the change process is 20→10→5→16→8→4→2→1.

According to the given number, verify this conjecture, and output the entire change sequence in reverse order starting from the last 1.

【enter】

Enter a positive integer  n .

【Output】

Output a number of positive integers separated by spaces, representing the sequence of changes in reverse order starting from the last 1.

【Input sample】

20

【Example of output】

1 2 4 8 16 5 10 20

【Code Explanation】

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n, a[5000], mark=1;
    cin >> n;
    a[mark] = n;
    mark++;
    while (n!=1) {
        if (n%2==0) n /= 2;
        else n = n * 3 + 1;
        a[mark] = n;
        mark++;
    }
    for (int i=mark-1; i>=1; i--) {
        cout << a[i] << " ";
    }
    return 0;
}

【operation result】

20
1 2 4 8 16 5 10 20

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/132645902