牛客练习赛25 A 因数个数和(数论分块)

题意:

q次询问,每次给一个x,问1到x的因数个数的和。

1<=q<=10 ,1<= x<=10^9 

1s

思路:

对1~n中的每个数i,i作为i,2i,3i,...的约数,一共作为n/i个数的约数

于是题目就转化为求$displaystyle sum_{i=1}^nlfloor frac{n}{i} floor$

数论分块$O(displaystyle sqrt{n})$解决

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
#include<functional>
    
#define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1
#define lowbit(x) ((x)&(-x)) 

using namespace std;

typedef double db;
typedef long double ldb;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL;

const db eps = 1e-6;
const int mod = 1e9+7;
const int maxn = 2e5+2;
const int maxm = 2e6+100;
const int inf = 0x3f3f3f3f;
const db pi = acos(-1.0);


int main() {
    int T;
    int n;
    scanf("%d", &T);
    while(T--){
        scanf("%d", &n);
        ll ans = 0;
        for(int l = 1, r; l <= n; l=r+1){
            r=n/(n/l);
            ans+=(r-l+1)*(n/l);
        }
        printf("%lld
", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wrjlinkkkkkk/p/9539611.html