题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1032php
1、题目要求ios
1)给出一个正整数n,若是n为奇数,则n=3n+1,不然n=n/2函数
2)设数n按1)中的运算方式,最少通过CollatzStep(n)次运算可以变成1spa
3)现给出两个正整数i和j,问数i和j之间全部数字里函数CollatzStep(n)可取到的最大值code
须要注意的是:ci
1)i与j的大小关系是不必定的get
2)最后输出结果时数字i和j须要按照顺序输出io
2、程序代码class
#include<iostream> using namespace std; //计算一个正整数通过奇偶归一猜测多少步能够到1 int CollatzStep(int n) { int step = 1; while(n != 1) { if(n % 2) { n = 3 * n + 1; } else { n /= 2; } step++; } return step; } int main() { int i, j, cur; //最小值i,最大值j,cur用来进行从i到j的遍历 int temp; //临时变量 int curstep; //数字cur迭代到1所花费的步数 int maxstep; //从i到j全部数字需花费的最大迭代步数 while(cin >> i >> j) { //统计最大迭代步数 maxstep = 0; for(cur = (i > j ? j : i); cur <= (i > j ? i : j); cur++) { curstep = CollatzStep(cur); maxstep = curstep > maxstep ? curstep : maxstep; } //输出结果 cout << i << ' ' << j << ' ' << maxstep << endl; } return 0; }
ENDstream