牛客:完全平方数

完全平方数

完全平方数

题解:
没想到本题竟然能用二分解决,二分真是无处不在啊。
题意很简单找[l,r]内的完全平方数,由于sqrt(1000000000)=31622。
所以答案必定在[0,31622]区间内,我们可以二分左右两个区间 :

  1. 左区间 L 2 l {L^2}≥l
  2. 右区间 R 2 > r {R^2>r}

那么[l,r]区间内完全平方数为 L 2 , ( L + 1 ) 2 , . . . . . , ( R 1 ) 2 {L^2,(L+1)^2,.....,(R-1)^2} ,个数总共为(R-L)。
即答案就是(R-L)。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>

int a[maxn];
int main()
{
	for(int i=0;i<maxn;i++) a[i]=i;
	int t;
	cin >> t;
	while(t--)
	{
		int l,r;
		cin >> l >> r;
		int L=0,R=maxn;
		L=lower_bound(a, a+maxn, sqrt(l))-a;
		R=upper_bound(a, a+maxn, sqrt(r))-a;
		cout << R-L << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/106652173