PAT B-level brushing record-1001 (3n + 1) conjecture (15 points)

Callatz's conjecture:
for any positive integer n, if it is even, then cut it in half; if it is odd, then cut (3n + 1) in half. This has been repeated repeatedly, and in the end, you must get n = 1 at a certain step. Karaz announced this conjecture at the 1950 World Mathematician Conference. According to legend, the teachers and students of Yale University were mobilized and tried to prove this seemingly silly and naive proposition. +1), so that some people say that this is a conspiracy, Karaz is deliberately delaying the progress of the American mathematics teaching and scientific research ...
Our topic today is not to prove Karaz conjecture, but for any given no more than 1000 The positive integer n of, simply count, how many steps (a few cuts) are needed to get n = 1?

Input format:

Each test input contains 1 test case, which gives the value of a positive integer n.

Output format:

The number of steps required to calculate from n to 1 is output.

Sample input:

3

Sample output:

5

Ideas

For this question, just follow the idea of ​​the question. If it is even, then n = n / 2, if it is odd, then n = (3 * n + 1) / 2, and continue to cycle back and forth until n == 1 Break it off, then remember cnt ++ every time you operate, and finally output the value of cnt is the required number of steps.

Code

#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main(){
	int n, cnt;
	cnt = 0;
	scanf("%d", &n);
	while(1){
		if(n==1) break;
		if(n%2==0){
			n = n/2;
			cnt++;
		}
		else{
			n = (3*n+1)/2;
			cnt++;
		}
	}
	printf("%d", cnt);
	return 0;
}
Published 54 original articles · won 27 · views 4967

Guess you like

Origin blog.csdn.net/weixin_42257812/article/details/105602366