筛法求约数和

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)

using namespace std;
long long l,r;
long long prime[N],f[N],g[N],cnt,ans;
bool vis[N];
void in(long long &x){
    long long y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(long long x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

void Euler(){
    For(i,2,r){
        if(!vis[i]){
            prime[++cnt]=i;
            f[i]=g[i]=i+1;
            vis[i]=1;
        }
        for(long long j=1;j<=cnt&&i*prime[j]<=r;j++){
            vis[i*prime[j]]=1;
            if(i%prime[j]==0){
                g[i*prime[j]]=g[i]*prime[j]+1;
                f[i*prime[j]]=f[i]/g[i]*g[i*prime[j]];
                break;
            }
            else{
                g[i*prime[j]]=prime[j]+1;
                f[i*prime[j]]=f[i]*f[prime[j]];
            }
        }
    }
}
int main(){
    in(l);in(r);
    Euler();
    For(i,l,r)
        ans+=f[i];
    o(ans);
    return 0;
}

 

posted @ 2019-08-05 10:01  WeiAR  阅读(393)  评论(0编辑  收藏  举报