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-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
#include
#include
#include
#include
#include
#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
,(ans%mod+mod)%mod);
}
return 0;
}