航电oj:The 3n + 1 problem

博客围绕航电oj的The 3n + 1 problem展开,题目要求在给定区间内求按特定规则(奇数变三倍加1,偶数除2,到1结束)的运转次数。作者分享了两版代码,第一版未注意坑未通过,第二版换方式计算通过,还强调英语和多审题的重要性。

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

**

航电oj:The 3n + 1 problem

**

#题目描述
在这里插入图片描述
在这里插入图片描述

#给你一个区间 要你求在这个区间内能运转这个规则的次数
#这个规则是 奇数就变为三倍加1 偶数就除2 是1了就结束

#知识点
英语? 语文?

#代码
这个题就是有坑 算法并不难
第一版 没有注意到坑 但我觉得这个比第二版好 可以看看 (这个是挂的!!!)

#include<cstdio>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stdio.h>
using namespace std;
int ans[1000020];
int n,m;
void math(int x)
{
    if(x == 1)
    {
        ans[x] = 1;
        return ;
    }
    if(x %2 ==0)//偶数
    {
        math(x/2);
        ans[x] = ans[x/2] +1;
    }
    else
    {
        math(3*x+1);
        ans[x] = ans[3*x+1] +1;
    }
}

int main()
{
    memset(ans,0,sizeof(ans));
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        double ark = 0;
        for(int i=n; i<=m; i++)
        {
            math(i);
            ark = max((int)ark,ans[i]);
        }
        cout <<n <<" "<<m<<" " << (int)ark <<endl;
    }
    return 0;
}

第二版 过了 换了种方式来算

#include<cstdio>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stdio.h>
using namespace std;
int n,m;
int main()//英语不好 就卡在坑上了 可恶啊w(゚Д゚)w
{
    while(scanf("%d%d",&n,&m)!=EOF)//大小不确定
    {
        int a,b;
        if(n > m)
        {
            a = m;
            b = n;
        }else
        {
            a = n;
            b = m;
        }
        int ark = 0;
        for(int i=a; i<=b; i++)
        {
            int temp = i;
            int ans = 0;
            while(temp != 1)
            {
                if(temp %2 == 0)
                {
                    temp = temp /2;
                    ans ++;
                }else
                {
                    temp = 3*temp+1;
                    ans ++;
                }
            }
            ark = max(ark,ans);
        }
        cout <<n <<" "<<m<<" " << ark+1 <<endl;//必需要是原来的n m 不能是a b
    }
    return 0;
}

#总结
英语好真是太重要了 ┭┮﹏┭┮ 多看看题总是好的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值