T5 区间平方加和
70分做法:直接按题目意思去写,但是会范围为 ,会超时,另一个是直接用 sqrt 的精度不够,一定要注意 sqrt 默认参数和返回值都是 double 类型,对 int 以上的数据范围开方时精度很大概率不够。当然这题也不能手写二分,时间复杂度会不够。
#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
//freopen("sum.in","r",stdin);
//freopen("sum.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int l,r,sum=0;
cin>>l>>r;
for(int i=l;i<=r;i++){
sum+=sqrt(i);
}
cout<<sum;
return 0;
}90分做法:暴力枚举 1e14 肯定超呀。其实我们会发现算术平方根只有 1e8 种,可以反向求解每个算术平方根对应的数有几个来计算即可。已经是正解了,只是数据范围还是存在问题 long*long会超范围。
#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
//freopen("sum.in","r",stdin);
//freopen("sum.out","w",stdout);
int l,r,sum=0;
cin>>l>>r;
for(int i=1;i<=10000000;i++){
int L=i*i;
int R=(i+1)*(i+1)-1;
if(R<l) continue;
if(L>r) break;
if(L<l) L=l;
if(R>r) R=r;
sum+=i*(R-L+1);
}
cout<<sum;
return 0;
}100分做法:第一个是可以使用高精度,一个是要用 __int128 。科普一下 __int128 的用法。__int128 是 128 位二进制数,也就是能存得下 long long * long long,运算速度会稍微的慢一丢丢,然后不能直接用 cin/cout 读写。一般会直接读进来一个 long long 然后赋值过去,或者逐个读字符类似快读的方法拼凑。输出时可以像我下面代码一样递归一位位转成可以输出的类型输出即可。
#include <bits/stdc++.h>
#define int long long
using namespace std;
void outInt128(__int128 x)
{
int num= x % 10;
if(x / 10 > 0)
outInt128(x / 10);
cout << num;
}
signed main()
{
int l, r;
cin>>l>>r;
__int128 sum = 0;
for (int i=1;i<=10000000;i++)
{
__int128 L=i*i;
__int128 R=(i+1)*(i+1)-1;
if(R<l) continue;
if(L>r) break;
if(R>r) R = r;
if(L<l) L = l;
sum+=i*(R-L+1);
}
outInt128(sum);
return 0;
}