萌新打卡 蓝桥杯 蓝桥学苑 每周一题之1. 3n+1 问题

题目没有传送门 在微信公众号里
直接上题目
在这里插入图片描述题目清楚明白 一看就是一道简单的模拟 一道水题 按照要求直接写出
马上阵亡
错误代码示范如下

#include <bits/stdc++.h>
using namespace std;
int main(){
	int i,j,cnt,max=1,m=0;
	cin>>i>>j;
	for(int n=i;n<=j;n++){
		m=n;
		cnt=1;
		while(m!=1){
			if(m%2==0){
				m=m/2;
			}
			else {
			m=3*m+1;
			}
			cnt++;
		}
		if(cnt>max)
		max=cnt;
	}
	cout<<i<<' '<<j<<' '<<max;
	return 0;
}

乍一看当然是对的了 提交之后发现两个错误点 1. 错在不能多组数据测试 2.不能处理输入数据第一个数大于第二个数的情况

#include <bits/stdc++.h>
using namespace std;
int main(){
	int i,j,t,cnt,max=1,m=0;
	while(scanf("%d %d",&i,&j)!=EOF){
		if(i>j){
			t=j;j=i;i=t;
		}
	for(int n=i;n<=j;n++){
		m=n;
		cnt=1;
		while(m!=1){
			if(m%2==0){
				m=m/2;
			}
			else {
			m=3*m+1;
			}
			cnt++;
		}
		if(cnt>max)
		max=cnt;
	}
	printf("%d %d %d\n",i,j,max);
	}
	return 0;
}

那么会发现 依旧不能AC(UVa上其实可以)
那是因为还有一个问题 问题3.中间计算过程会超过 int溢出,故需要选择 long long。

#include <bits/stdc++.h>
using namespace std;
int main(){
	long long i,j,m=0;
	int t,cnt,max=1;
	while(cin>>i>>j){
		if(i>j){
			t=j;j=i;i=t;
		}
	for(int n=i;n<=j;n++){
		m=n;
		cnt=1;
		while(m!=1){
			if(m%2==0){
				m=m/2;
			}
			else {
			m=3*m+1;
			}
			cnt++;
		}
		if(cnt>max)
		max=cnt;
	}
	cout<<i<<' '<<j<<' '<<max;
	}
	return 0;
}

另外本题还可以是用记忆型搜索 用hashmap进行优化 具体方法我就不会啦

欢迎各位神犇来指点!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值