牛客练习赛25 - A 因数个数和

原文地址:http://www.cnblogs.com/liubilan/p/9531916.html    

借鉴:https://blog.csdn.net/zzcblogs/article/details/78816533

1~n 约数的个数的和实际就是看 1~n 在这些数中出现过多少次,例如 1是1~n每个数的因数,所以对1这个因数来说,出现了n/1次,以此类推;

发现答案 1/n+2/n+3/n+……+n/n 其实就是函数 y=1/x 在1~n 上的离散和,因为函数关于直线 y=x 对称,求 1~√n 离散合再减去重复的地方即可;

代码如下:

#include<iostream>
#include<cmath>
using namespace std;

int n, q;
int main()
{
    ios::sync_with_stdio(false);
    cin>>q;
    while(q--) {
        cin>>n;
        long long ans=0, t=sqrt((double)(n));
        for(int i=1; i<=t; i++)
            ans += n/i;
        ans = ans*2-t*t;
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PleasantlY1/article/details/82048988