Calculation 2
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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互质的数,然和求和。就是一个简单的欧拉函数的拓展,n的数中,与n互质的数的总和为:φ(x) * x / 2 (n>1)。其实就是n*(互质的数的个数)/2。知道了这些就很简单了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod = 1e9+7;
//先将所有的互质的数的个数给求出来
ll eular(ll n)
{
ll ans = n;
for(int i=2;i<=sqrt(n);i++)
{
if(n%i == 0)
{
ans = ans/i*(i-1);
ans %= mod;
while(n%i == 0)
{
n /= i;
}
}
}
if(n > 1)
ans = ans/n*(n-1);
return ans;
}
int main()
{
ll n;
while(scanf("%lld",&n) && n)
{
ll sum = (n-1)*n/2;
ll sum2 = n*eular(n)/2;//按照这个公式可以知道所有的互质的数的和
printf("%lld
",(sum-sum2)%mod);
}
return 0;
}