poj 1207 The 3n + 1 problem

本文介绍了一个关于数列处理的编程挑战,重点在于通过循环和条件判断来找出特定数值范围内数列变化的最大步数。文章提供了完整的C++实现代码,并特别强调了输入验证的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//这题贡献了一次WA,原因是由于没有考虑到输入的两个数中,有可能后面的数大于前面的数 ! 
#include "iostream"
using namespace std;

int solve(int num)
{
    int i, c = 1;
    if (num == 1) return c;
    else
    {
        while (num != 1)
        {
            if (num % 2)
            { 
               num = num * 3 + 1;
               c++;
            }
            else 
            {
               num = num / 2;
               c++;
            }
        }
        return c;
    }
    
}

int main()
{
    int a, b, maxc, i, temp, ansa, ansb;
    while (cin >> a >> b)
    {
          maxc = 0;
          ansa = a, ansb = b;
          if (a > b)//作判断,如果后一个数大于前一个数,就交换位置! 
          {
              temp = a;
              a = b;
              b = temp;
          }
          for (i = a ; i <= b; i++)
          {
              temp = solve(i);
              if (temp > maxc)
                 maxc = temp;
          }
          cout << ansa << " " << ansb << " " << maxc << endl;
    }
    
    system("pause");
} 


/*
1 10
100 200
201 210
900 1000
10000 1
500 200
200 200
1 1
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值