l o n g l o n g long\ long long long的加法溢出情况:
l o n g l o n g long\ long long long能储存的数据范围: [ − 2 63 , 2 63 − 1 ] [-2^{63},2^{63}-1] [−263,263−1]。
1.当 a , b > 0 , a + b ≥ 2 63 a,b>0,a+b\geq2^{63} a,b>0,a+b≥263
a + b ∈ [ 2 63 , 2 64 − 2 ] a+b\in[2^{63},2^{64}-2] a+b∈[263,264−2]。
根据计算机的溢出处理规则:需要对最高位 2 64 2^{64} 264取模。
取模后变为: [ 2 63 , − 2 ] [2^{63},-2] [263,−2]。
但是 2 63 2^{63} 263在计算机会自动转为: − 2 63 -2^{63} −263。
所以范围变为: [ − 2 63 , − 2 ] [-2^{63},-2] [−263,−2]。
2.当 a < 0 , b < 0 , a + b ≥ 0 a<0,b<0,a+b\geq0 a<0,b<0,a+b≥0。
a + b ∈ [ − 2 64 , − 2 63 − 1 ] a+b\in[-2^{64},-2^{63}-1] a+b∈[−264,−263−1]。
同样取模后变为: [ 0 , 2 63 − 1 ] [0,2^{63}-1] [0,263−1]
3.其他情况不会溢出。
对应的 P A T PAT PAT 1065 A+B and C (64bit)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e3+5,M=2e4+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a,b) memset(a,b,sizeof a)
#define lx x<<1
#define rx x<<1|1
#define reg register
#define PII pair<int,int>
#define fi first
#define se second
#define pb push_back
#define il inline
int t;
int main(){
scanf("%d",&t);
for(int i=1;i<=t;i++){
ll a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
ll d=a+b;
printf("Case #%d: ",i);
if(a>0&&b>0&&d<0) puts("true");
else if(a<0&&b<0&&d>=0) puts("false");
else if(d>c) puts("true");
else puts("false");
}
return 0;
}
值得注意的是: a + b a+b a+b这里先得用一个变量 l o n g l o n g long\ long long long 储存起来,再与 c c c比较,不然会出错。