hdoj f(n) 2582 (GCD打表&找规律)好题

来源:互联网 发布:sql nvl函数 编辑:程序博客网 时间:2024/06/05 18:47

f(n)

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 378    Accepted Submission(s): 230


Problem Description
This time I need you to calculate the f(n) . (3<=n<=1000000)

f(n)= Gcd(3)+Gcd(4)+…+Gcd(i)+…+Gcd(n).
Gcd(n)=gcd(C[n][1],C[n][2],……,C[n][n-1])
C[n][k] means the number of way to choose k things from n some things.
gcd(a,b) means the greatest common divisor of a and b.


 

Input
There are several test case. For each test case:One integer n(3<=n<=1000000). The end of the in put file is EOF.


 

Output
For each test case:
The output consists of one line with one integer f(n).


 

Sample Input
326983


 

Sample Output
337556486

 

通过打表找GCD的规律的话,你会发现如下规律:
GCD(n),当n只有一个质因子的时候GCD(n)不会为1,此时GCD等于n的这个唯一的质因子。

#include<stdio.h>#include<string.h>#include<algorithm>#define ll __int64#define N 1000010using namespace std;ll p[N];bool flag[N];ll sum[N];void init(){__int64 i,j,num=0;for(i=2;i<=N;i++){if(!flag[i]){p[num++]=i;for(j=i*i;j<=N;j+=i)flag[j]=true;}}}ll solve(ll n){ll i,k,ans=0;for(i=0;p[i]*p[i]<=n;i++){if(n%p[i]==0){n/=p[i];while(n%p[i]==0)n/=p[i];k=p[i];ans++;}if(ans>=2)return 1;}if(n>1){ans++;k=n;}if(ans>=2)return 1;elsereturn k;}int main(){ll n,i;init();for(i=3;i<=N;i++){if(flag[i])sum[i]=sum[i-1]+solve(i);elsesum[i]=sum[i-1]+i;}while(scanf("%d",&n)!=EOF)printf("%I64d\n",sum[n]);return 0;}


 

0 0
原创粉丝点击