HDU

( ext{Solution})

就是求出 ([1,n]) 中与 (n) 互质的数的和。

这里有个结论:

(ans) 就是 (phi(n) imes n/2)

在证明之前有一个结论:如果 (gcd(i,n)=1),那么 (gcd(n-i,n)=1)

假设 (gcd(n-i,n)=x(x≠1))。那么有 (n-i=a imes x,n=b imes x),那么 (i=(b-a) imes x)。那 (gcd(i,n)) 一定是 (x) 的非零倍数,不会等于 (1)

有了这个结论,我们就可以将 ([1,n]) 的与 (n) 互质的数两两配对,即为 (ans)

另外,我们的 (/2) 是必须放后面的。考虑不同的原因在于 (phi(n)) 是否为偶。显然只有 (phi(2)=1) 为奇。其他不会有 (i+i=n) 的情况,因为这样的 (i) 一定与 (n) 不互质。

( ext{Code})

#include <cstdio>

#define rep(i,_l,_r) for(register signed i=(_l),_end=(_r);i<=_end;++i)
#define fep(i,_l,_r) for(register signed i=(_l),_end=(_r);i>=_end;--i)
#define erep(i,u) for(signed i=head[u],v=to[i];i;i=nxt[i],v=to[i])
#define efep(i,u) for(signed i=Head[u],v=to[i];i;i=nxt[i],v=to[i])
#define print(x,y) write(x),putchar(y)

template <class T> inline T read(const T sample) {
	T x=0; int f=1; char s;
	while((s=getchar())>'9'||s<'0') if(s=='-') f=-1;
	while(s>='0'&&s<='9') x=(x<<1)+(x<<3)+(s^48),s=getchar();
	return x*f;
}
template <class T> inline void write(const T x) {
	if(x<0) return (void) (putchar('-'),write(-x));
	if(x>9) write(x/10);
	putchar(x%10^48);
}
template <class T> inline T Max(const T x,const T y) {if(x>y) return x; return y;}
template <class T> inline T Min(const T x,const T y) {if(x<y) return x; return y;}
template <class T> inline T fab(const T x) {return x>0?x:-x;}
template <class T> inline T Gcd(const T x,const T y) {return y?Gcd(y,x%y):x;}
template <class T> inline T Swap(T &x,T &y) {x^=y^=x^=y;}

const int mod=1e9+7;

int n;

int phi(int x) {
	int r=x;
    for(int i=2;i*i<=x;++i) {
    	if(x%i) continue;
        r=r/i*(i-1);
        while(x%i==0) x/=i;
    }
    if(x>1) r=r/x*(x-1);
    return r;
}

int main() {
    while(233) {
    	n=read(9);
    	if(!n) break;
    	print((1ll*n*(n-1)/2%mod-1ll*phi(n)*n/2%mod+mod)%mod,'
');
    }
    return 0;
}

原文地址:https://www.cnblogs.com/AWhiteWall/p/13603533.html