【神秘题 整数溢出】牛客小白月赛71 C-猫猫与数列

文章介绍了在编程比赛中遇到的问题,即在计算数列时可能会超过longlong的范围,解决方案是使用__int128类型。文中提供了读取和打印__int128的方法,并展示了如何进行数列的模拟计算。当计算结果过大时,会返回溢出标志。代码示例包括直接相加和计算数列的特定项。
摘要由CSDN通过智能技术生成

被教育了

学到了一些只有我不知道的常识

C-猫猫与数列_牛客小白月赛71(重现赛) (nowcoder.com)

题意:

思路:

直接模拟即可

值得注意的是,他在算数列的过程中可能会爆long long,因此在算的时候注意开__int128,这样就算爆long long也能和1e18比较

 

__int128可以四则运算,但是不能输入输出,因此要专门写一个函数实现输入输出

Code:

#include <bits/stdc++.h>
using namespace std;
inline __int128 read(){
    __int128 x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9'){
        if(ch == '-')
            f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9'){
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}
inline void print(__int128 x){
    if(x < 0){
        putchar('-');
        x = -x;
    }
    if(x > 9)
        print(x / 10);
    putchar(x % 10 + '0');
}
int main(void){
    __int128 a = read();
    __int128 b = read();
    print(a + b);
    cout << endl;
    return 0;
}

 关于这道题:

#include<bits/stdc++.h>
using namespace std;
const long long M=1e18;
long long A[10005];
__int128 calc(__int128 a,long long b){
	__int128 res=1;
	while(b>0){
		if(b&1)res=res*a;
		if(res>M||a>M)return M+10;
		a=a*a;
		b>>=1;
	}
	return res;
}
int main(){
    
    
	scanf("%lld %lld",&A[1],&A[2]);
	int n=2;
	for(int i=3;i;i++){
		A[i]=calc(A[i-2],A[i-1]);
		if(A[i]>M){
			n=i-1;
			break;
		}
	}
	printf("%d\n",n);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值