1004_History_repeat_itself

题目:


官方题解:

1)To solve the N-th non-square number:
There is a number K:  K^2<N+K<(K+1)^2
Thus : K^2+1<= N+K <= (K+1)^2-1
So: (K-1/2)^2+3/4=K^2-K+1 <= n <= K^2 +K = (K+1/2)^2 -1/4
That is to say: K-1/2 < (N)^1/2 <= K+1/2
the N-th non-square number is : N+K (K is the nearest integer from N^1/2);


And for many team, you can just use circular statement, it's simple and fast.


2)To get the sum:
for any i , there exists a integer K : K^2<=i<(K+1)^2;
to find the K:
the first (1^2) i : 1
the next  (2^2) i : 2
...
the next  (K^2) i : K
...
If Sum(K^2) <= N <= Sum( (K+1)^2), R=N-Sum(K^2);
add them up : 1^2*1 + 2^2*2 + ... + K^2*K + R*(K+1) ;
use the knowlege of college math,
Then You Got It! 
M=N^(1/2)-1, drop the number after the decimal point.
the Ans=(M*(M+1)*(2*M+1))/3 +(M+1)*M/2+ (M+1)*(N-(M+1)*(M+1)+1);




3)
I think this problem is simple, hope that most of you can solve it.


个人理解:

解题的关键在于找到离第M个非平方数最近且小于它的平方数。本人最初的想法是预处理出2^31以内的平方数,再用二分查找去找第M个非平方数。但是题解给出的方法显然要跟好些。

标程:

#include <iostream>
#include <cmath>
using namespace std;
typedef __int64 LL;
int main()
{
 //   freopen("data.in", "r", stdin);
 //   freopen("data.out", "w", stdout);
    LL n,m,ans,total;
    cin>>total;
    while (total--)
    {
        cin>>n;
        n+=sqrt(n)+0.5;
        m=sqrt(n)-1;
        ans=(m*(m+1)*(2*m+1))/3 +(m+1)*m/2+ (m+1)*(n-(m+1)*(m+1)+1);
        cout<<n<<" "<<ans<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值