Calculation 2
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5342 Accepted Submission(s): 2199
Problem Description
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
题意:求解1~n与n不互质的数的和。
解析:典型的欧拉函数应用。
利用欧拉函数即可求解,1~n比n小且与n互素的数的总和为 * sum(n) = n * phi(n) / 2;那么可以先求出1~n-1的总和,然后 * 减去sum(n)即可。
#include<bits/stdc++.h>
using namespace std;
#define e exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define mem(a,b) memset(a,b,sizeof(a))
int gcd(int a,int b){return b?gcd(b,a%b):a;}
ull euler(ull n)
{
ull res=n,a=n;
for(ull i=2;i*i<=a;i++)
{
if(a%i==0)
{
res=res/i*(i-1);
while(a%i==0) a/=i;
}
}
if(a>1) res=res/a*(a-1);
return res;
}
int main()
{
ull n;
while(~scanf("%llu",&n),n)
{
ull sum=n*(1+n)/2-n,ans;
ans=sum-euler(n)*n/2;
printf("%llu\n",ans%mod);
}
return 0;
}