关于欧拉函数,感谢大佬分享:https://blog.csdn.net/ydd97/article/details/47805419
先讲欧拉函数:
欧拉函数就是指:对于一个正整数n,小于n且和n互质的正整数(包括1)的个数,记作φ(n) 。
欧拉函数的通式:φ(n)=n*(1-1/p1)*(1-1/p2)*(1-1/p3)*(1-1/p4)…..(1-1/pn),其中p1, p2……pn为n的所有质因数,n是不为0的整数。φ(1)=1(唯一和1互质的数就是1本身)。
对于上述的通式一定要牢记在心,因为这是计算欧拉函数最重要的一步。 切记切记~~~~
代码:
int phi(int n){//求欧拉函数的代码
int ans=n;
for(int i=2;i*i<=n;i++){
if(n%i==0){//如果是n的质因子
ans-=ans/i;//模拟欧拉函数通式
while(n%i==0)n/=i;//在欧拉函数中每个质因子只用一下
}
}
if(n>1)ans-=ans/n;//如果N不是1,那么n一定也是一个质因子
return ans;
}
然后题描述:
Given a positive integer N, your task is to calculate the sum of the positive integers less than N which are not coprime to N. A is said to be coprime to B if A, B share no common positive divisors except 1.
Input
For each test case, there is a line containing a positive integer N(1 ≤ N ≤ 1000000000). A line containing a single 0 follows the last test case.
Output
For each test case, you should print the sum module 1000000007 in a line.
Sample Input
3 4 0
Sample Output
0 2
大意就是給一个数,然后求小于这个数的所有和它不互质的数的和。
思路:所有小于它的和,减去小于它的质数的和。
质数之和 N*phi(N)/2 (如果 i 是互质的 那么N-i也是互质的 那么i + N- i == N 除以2是因为每个数被算了两遍 )
公式 ans=N*(N-1)/2 - N*phi(N)/2;
代码:
//求小于N的不和N互质的数的和
#include<bits/stdc++.h>
using namespace std;
int phi(int n){//求欧拉函数的代码
int ans=n;
for(int i=2;i*i<=n;i++){
if(n%i==0){
ans-=ans/i;
while(n%i==0)n/=i;
}
}
if(n>1)ans-=ans/n;
return ans;
}
int main(){
int t;
cin>>t;
while(t){
cout<<t*(t-1)/2-t*phi(t)/2<<endl;
cin>>t;
}
return 0;
}