The 3n + 1 problem UVA - 100 (细节)

The 3n + 1 problem UVA - 100




题意:

给出n, n为偶数则n = n/2, 奇数则n = n*3+1, 直至n==1

题解:

经典的3N+1问题, 主要要写循环不要写递归, 否则会爆, 以及换行的格式问题

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1<<30;
const LL maxn = 1e6+10;

int main()
{
	int i, j;
	while(cin >> i >> j){
		int n = 0;
		for(int k = min(i, j); k <= max(i, j); k++){
            int cnt = 1, cur = k;
            while(cur!=1){
                cur = (cur%2==0)?cur>>1:cur*3+1;
                cnt++;
            }
            n = max(n, cnt);
		}
		cout << i << ' ' << j << ' ' << n << endl;
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/88628125