CodeForces 546D

题意略。

思路:开始傻傻地还单个去分解[1,5000000]中每一个数字的因子,那必然超时的啊。

正确的做法是用类似于埃式筛法那样预处理一遍。复杂度:O((n / 2 + n / 3 + .....+ )) = O(nlogn)。

详见代码:

#include<bits/stdc++.h>
#define maxn 5000005
using namespace std;
typedef long long LL;

LL sum[maxn];

void init(){
    memset(sum,0,sizeof(sum));
    for(int i = 2;i < maxn;++i){
        if(sum[i] == 0){
            for(int k = i;k < maxn;k += i){
                int temp = k;
                while(temp % i == 0){
                    temp /= i;
                    ++sum[k];
                }
            }
        }
    }
    for(int i = 1;i < maxn;++i){
        sum[i] += sum[i - 1];
    }
}

int main(){
    int t;
    init();
    scanf("%d",&t);
    while(t--){
        int a,b;
        scanf("%d%d",&a,&b);
        LL ans = sum[a] - sum[b];
        printf("%lld
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tiberius/p/8544145.html