一個合數的真因數是指這個數不包括其自己的全部因數,ios
例如 6 的正因數有1, 2, 3, 6,其中真因數有 1, 2, 3。git
一個合數的最大真因數則是這個數的全部真因數中最大的一個,例如 6 的最大真因數爲 3。spa
給定正整數 l 和 r,請你求出 l 和 r 之間(包括 l 和 r)全部合數的最大真因數之和。3d
輸入共一行,包含兩個正整數 l 和 r。保證 l ≤ r。code
輸出共一行,包含一個整數,表示 [l,r] 內全部合數的最大真因數之和。blog
1 10ip
17get
【樣例 1 解釋】input
在 1 至 10 之間的合數有 4, 6, 8, 9, 10,string
它們的最大真因數分別爲 2, 3, 4, 3, 5,
所以最大真因數之和爲 2 + 3 + 4 + 3 + 5 = 17。
【樣例 2 輸入】
101 1000
【樣例 2 輸出】
163446
【樣例 3 輸入】
180208 975313
【樣例 3 輸出】
151642139152
【樣例 4 輸入】
339762200 340762189
【樣例 4 輸出】
112318862921546
【樣例 5 輸入】
2500000000 5000000000
【樣例 5 輸出】
3094668961678105770
要求合數的最大真因數,至關於求合數除以其最小質因子。
再Min_25篩求素數和的過程當中:
\[ g(n,j)= \begin{cases} g(n,j-1)&P_j^2> n\\ g(n,j-1)-f(P_j)\cdot[g(\frac{n}{P_j},j-1)-\sum_{i=1}^{j-1}f(P_i)]&P_j^2\leq n \end{cases} \]
其中
\[ g(\frac{n}{P_j},j-1)-\sum_{i=1}^{j-1}f(P_i) \]
求得的即是最小質因子爲\(P_j\)的合數之和。
咱們只需在處理\(g\)的時候統計答案便可。
#include<iostream> #include<cstring> #include<cmath> #include<algorithm> #include<cstdio> #include<iomanip> #include<cstdlib> #define MAXN 0x7fffffff typedef unsigned long long LL; const int N=250005; using namespace std; inline LL Getint(){register LL x=0,g=1;register char ch=getchar();while(!isdigit(ch)){if(ch=='-')g=-1;ch=getchar();}while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}return x*g;} int prime[N],tot;bool vis[N]; LL sqr,w[N],g[N],sp[N]; int id1[N],id2[N],m; void Pre(int n){ for(int i=2;i<=n;i++){ if(!vis[i])prime[++tot]=i,sp[tot]=sp[tot-1]+i; for(int j=1;j<=tot&&1ll*i*prime[j]<=n;j++){ vis[i*prime[j]]=1; if(i%prime[j]==0)break; } } } LL Solve(LL n){ tot=m=0; sqr=sqrt(n),Pre(sqr); for(LL i=1,j;i<=n;i=j+1){ j=n/(n/i),w[++m]=n/i; g[m]=w[m]*(w[m]+1)/2-1; if(w[m]<=sqr)id1[w[m]]=m;else id2[j]=m; } LL ans=0; for(int j=1;j<=tot;j++){ for(int i=1;i<=m&&(LL)prime[j]*prime[j]<=w[i];i++){ int k=(w[i]/prime[j]<=sqr)?id1[w[i]/prime[j]]:id2[n/(w[i]/prime[j])]; if(i==1)ans+=g[k]-sp[j-1]; g[i]-=prime[j]*(g[k]-sp[j-1]); } } return ans; } int main(){ LL l=Getint(),r=Getint(); cout<<Solve(r)-Solve(l-1); return 0; }