它会因为大输入超时而终止错误t.找到给定范围内的完美正方形的数量
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double s,e,i;
int t;
scanf("%d",&t);
for (;t>0;t--)
{
int cnt=0;
scanf("%lf%lf",&s,&e);
for (i=s;i<=e;i++)
{
if (sqrt(i)==ceil(sqrt(i)))
cnt++;
}
printf("%d\n",cnt);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有一个技巧.只需找到下限和上限的平方根,取其积分部分,然后从上限减去下界的整数部分.您还需要检查下限是否是完美的正方形.如果它然后添加1到差异.
例如:与完全平方数1和100是10 - 1 = 9.因为1也是一个完美的正方形因此添加1,因此结果将是10.
int result = (int)sqrt(upper_bound) - (int)sqrt(lower_bound);
if(lower_bound == (int)sqrt(lower_bound)*(int)sqrt(lower_bound))
++result;
Run Code Online (Sandbox Code Playgroud)
请注意,我考虑了上限和下限.