Calculation 2
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2570 Accepted Submission(s): 1073
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
思路:先求互质的和,在用前n-1个数的和来减。
此处用到欧拉函数。(对于一个数n,在小于n的数中与n互质的数的个数)
一个关于gcd的定理。gcd(n,i)=1,那么gcd(n,n-i)=1,互质的所有数的和,sum=(eular(n)*n/2) (n-i与i和为n,个数为eular/2个)
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 1000000001
#define mod 1000000007
using namespace std;
typedef long long ll;
ll eular(ll n)
{
ll num=1;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
num*=(i-1);
n/=i;
while(n%i==0)
{
n/=i;
num*=i;
}
}
}
if(n>1) num*=(n-1);
return num;
}
int main()
{
ll n;
while(scanf("%d",&n),n)
{
ll ans;
ans=n*(n+1)/2-n;
ans-=(eular(n)*n/2);//由欧拉函数求出与n互质的数,减去互质数的和
printf("%I64d\n",(ans%mod+mod)%mod);
}
return 0;
}