【牛客练习赛 25】A 因数个数和

题目地址:https://www.nowcoder.com/acm/contest/158/A

参考博客: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 离散合再减去重复的地方即可;

 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 
 5 int n, q;
 6 int main()
 7 {
 8     ios::sync_with_stdio(false);
 9     cin>>q;
10     while(q--) {
11         cin>>n;
12         long long ans=0, t=sqrt((double)(n));
13         for(int i=1; i<=t; i++)
14             ans += n/i;
15         ans = ans*2-t*t;
16         cout<<ans<<endl;
17     }
18     return 0;
19 }

 

posted @ 2018-08-24 20:39  liubilan  阅读(395)  评论(0编辑  收藏  举报