GCD Extreme (II) 欧拉函数的应用

Problem J
GCD Extreme (II)
Input: Standard Input

Output: Standard Output

Given the value of N, you will have to find the value of G. The definition of G is given below:

 

Here GCD(i,j) means the greatest common divisor of integer i and integer j.

For those who have trouble understanding summation notation, the meaning of G is given in the following code:

G=0;

for(i=1;i<N;i++)

for(j=i+1;j<=N;j++)

{

    G+=gcd(i,j);

}

/*Here gcd() is a function that finds the greatest common divisor of the two input numbers*/

Input

The input file contains at most 100 lines of inputs. Each line contains an integer N (1<N<4000001). The meaning of N is given in the problem statement. Input is terminated by a line containing a single zero. 

Output

For each line of input produce one line of output. This line contains the value of G for the corresponding N. The value of G will fit in a 64-bit signed integer.

Sample Input                              Output for Sample Input

10

100

200000

0

 

67

13015

143295493160

 


Problemsetter: Shahriar Manzoor

Special Thanks: SyedMonowarHossain

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<string>
#include<map>
#include<stack>
#include<set>
#include<iostream>
#include<vector>
#include<queue>
//ios_base::sync_with_stdio(false);
//#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;
#define sz(v) ((int)(v).size())
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define repf(i, a, b) for (int i = (a); i <= (b); ++i)
#define repd(i, a, b) for (int i = (a); i >= (b); --i)
#define clr(x) memset(x,0,sizeof(x))
#define clrs( x , y ) memset(x,y,sizeof(x))
#define out(x) printf(#x" %d
", x)
#define sqr(x) ((x) * (x))
typedef long long LL;

const int INF = 1000000000;
const double eps = 1e-8;
const int maxn = 4000100;

int sgn(const double &x) {  return (x > eps) - (x < -eps); }

int phi[maxn];
void pre(int n)
{
     repf(i,2,n)
         phi[i]  = 0;
     phi[1] = 1;
     repf(i,2,n)
     {
        if(!phi[i])
        {
            for(int j = i;j<=n;j+=i)
            {
                if(!phi[j])
                    phi[j] = j;
                phi[j] = phi[j]/i*(i-1);
            } 
        }
     }
}

LL ans[maxn];
LL temp[maxn];
int main() 
{
    //freopen("in.txt","r",stdin);
    pre(4000000);
    clr(temp);
    repf(i,1,4000000)
     for(int j = i*2;j<= 4000000;j+=i)
     {
         temp[j] += i*phi[j/i];
     }
    
    ans[2] = temp[2];
    
    repf(i,3,4000000)
        ans[i] = ans[i-1] + temp[i];
    int n;
    while(cin>>n && n)
    {
         cout<<ans[n]<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/DreamHighWithMe/p/3400006.html