【HDU - 4342】History repeat itself(数学)

BUPT2017 wintertraining(15) #8C

题意

求第n(n<2^32)个非完全平方数m,以及\(\sum_{i=1}^m{\lfloor\sqrt i\rfloor}\)

题解

设1~m中有x个完全平方数(\(1^2,2^2,3^2,...,x^2\))。
那么有

\[\begin{cases} n+x=m\\ x^2 < m\\ (x+1)^2 \ge m \end{cases} \]

等价于求满足\(m-\sqrt m < n\)的m的最大值。
于是可以二分。
预处理出\(\lfloor\sqrt i\rfloor\)的前缀和,i出现(i*2+1)次,注意要转换为long long。

代码

#include <cstdio>
#include <cmath>
#define ll long long
int t;
const int N=1LL<<16;
ll n,x,ans,a[N];
int main(){
	for(int i=1;i<=N;i++)
		a[i]=a[i-1]+(ll)(i*2+1)*i;
	scanf("%d", &t);
	while(t--){
		scanf("%lld", &n);
		ll l=1, r=1LL<<32;
		while(l<r){
			ll m=l+r>>1;
			if(m-(ll)sqrt(m)<n)
				l=m+1;
			else
				r=m;
		}
		x=l;
		ll g=floor(sqrt(x));
		ans=a[(int)g-1]+(x-g*g+1)*g;
		printf("%lld %lld\n", x, ans);
	}
	return 0;
}
posted @ 2017-07-05 13:54  水郁  阅读(269)  评论(4编辑  收藏  举报
……