Test instructions: Sum (gcd (i,j), 1<=i<j<=n)1<n<4000001
Ideas:
1. Establish a recursive relationship, S (n) =s (n-1) +gcd (1,n) +gcd (2,n) +......+GCD (n-1,n);
2. Set f (n) =gcd (1,n) +gcd (2,n) +......+GCD (n-1,n).
GCD (X,n) =i is an approximate (x<n) of N, classified according to this approximate. A constraint that satisfies the GCD (x,n) =i has g (n,i), then f (n) =sum (I*g (n,i)).
The GCD (x,n) =i is equivalent to gcd (x/i,n/i) = 1, so g (n,i) is equivalent to Phi (n/i). Phi (x) is an Euler function.
3. Reduce the complexity of time. Pretreatment of phi[x] table by sieve method
By using the Sieve method, the enumeration factor of F (x) is pretreated, and all multiples of the solution are updated.
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <cctype>5#include <cstring>6#include <vector>7#include <cassert>8 9 using namespacestd;Ten Const intMAXN =4000010; One #defineLL Long Long A #defineCLC (A, B) memset (A,b,sizeof (a)) - LL S[MAXN],F[MAXN]; - LL PHI[MAXN]; the voidPhi_table (intN) - { - for(intI=2; i<=n;i++) -phi[i]=0; +phi[1]=1; - for(intI=2; i<=n;i++) + { A if(phi[i]==0) at { - for(intj=i;j<=n;j+=i) - { - if(!Phi[j]) -phi[j]=J; -phi[j]=phi[j]/i* (I-1); in } - } to } + } - the intMain () * { $ phi_table (MAXN);Panax NotoginsengCLC (F,0); - for(intI=1; i<=maxn;i++) the { + for(intn=i*2; n<=maxn;n+=i) Af[n]+=i*phi[n/i]; the } +s[2]=f[2]; - for(intn=3; n<=maxn;n++) $s[n]=s[n-1]+F[n]; $ intN; - while(SCANF ("%d",&N), N) - { theprintf"%lld\n", S[n]); - }Wuyi return 0; the}
View Code
uva11426 GCD Extreme (II)