两道欧拉函数变式题目(HDU 3501 Calculation 2&&HDU 1787 )

1.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的与n互质数之和。互质也就是两者最大公约数为1

#include<bits/stdc++.h>
using namespace std;
#define ll __int64
ll phi(ll n)
{
    ll res=n;
    for(ll i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            res=res/i*(i-1);
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1)res=res/n*(n-1);
    return res;
}
int main()
{
    ll n;
    while(cin>>n&&n)
    {
        ll m=phi(n);
        ll k=m*n/2;//k是满足条件与n互素数的和
        k=n*(n+1)/2-n-k;//n*(n+1)/2为1---n所有数的和
        cout<<k%1000000007<<endl;
    }
}

2.给你一个整数N,求范围小于N中的整数中,与N的最大公约数大于1的整数的个数。

欧拉函数求出的是小于n中与n最大公约数为1的个数所以

ans = n - φ(N) - 1。

#include<bits/stdc++.h>
using namespace std;
#define ll __int64
ll phi(ll n)
{
    ll res=n;
    for(ll i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            res=res/i*(i-1);
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1)res=res/n*(n-1);
    return res;
}
int main()
{
    ll n;
    while(cin>>n&&n)
    {
        ll m=phi(n);
        ll k=n-m-1;
        cout<<k<<endl;
    }
}

也可以用筛法做

#include<bits/stdc++.h>
using namespace std;
#define ll __int64
const ll N =100000000;
ll phi[N+10],prime[N+10],tot,ans;//用筛法要注意数组不要越界,注意n的范围
bool mark[N+10];
void ok()
{
    int i,j;
    phi[1]=1;
    for(i=2;i<=N;i++)
    {
        if(!mark[i])
        {
            prime[++tot]=i;
            phi[i]=i-1;
        }
        for(j=1;j<=tot&&i*prime[j]<=N;j++)
        {
            mark[i*prime[j]]=1;
            if(i%prime[j]==0)
            {
                phi[i*prime[j]]=phi[i]*prime[j];
                break;
            }
            else
            {
                phi[i*prime[j]]=phi[i]*(prime[j]-1);
            }
        }
    }

}
int main()
{
    ok();
    ll n;
    while(cin>>n)
    {
        ll m=phi[n];
        ll k=n-m-1;
        cout<<k<<endl;

    }
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/81501641