欧拉函数的应用,以后看到互质的数第一个就要想到欧拉函数。今天又学到了好多家伙。

欧拉定理:

欧拉定理表明,若n,a为正整数,且n,a互质,(a,n) = 1,则a^φ(n) ≡ 1 (mod n) 

 

费马小定理:

且(a,p)=1,那么 a^(p-1) ≡1(mod p) 假如p是质数,且a,p互质,那么 a的(p-1)次方除以p的余数恒等于1 。

 

筛选法求欧拉函数,时间复杂度O(nloglogn), CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
using namespace std;

const int SIZE = 1001;
int phi[SIZE];

void init()
{
    int i, j;
    memset(phi, 0sizeof(phi));
    phi[1] = 1;
    for(int i = 2; i < SIZE; i++) if(!phi[i])
    {
        for(j = i; j < SIZE; j+=i)
        {
            if(!phi[j]) phi[j] = j;
            phi[j] = phi[j] / i * (i-1);
        }
    }
    return ;
}

int main()
{
    init();
    int n;
    while(~scanf("%d", &n))
    {
        for(int i = 1; i <= n; i++)
        {
            printf(i != n?"%d ":"%d\n", phi[i]);
        }
    }
    return 0;

} 


求一个整数的欧拉函数值,CODE: 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
using namespace std;


int euler_phi(int n)
{
    int m = floor(sqrt(n+0.5));
    int ans = n;
    for(int i = 2; i <= m; i++) if(n%i == 0)
    {
        ans = ans / i * (i-1);
        while(n%i == 0)
        {
            n /= i;
        }
    }
    if(n > 1) ans = ans / n *(n-1);
    return ans;
}



int main()
{
    int n;
    while(~scanf("%d", &n), n)
    {
        printf("%d\n", euler_phi(n));
    }
    return 0;
}

 

 

 

题目大意:求小于n并且与n不互质的数的和。

思路:由于数据范围比较大,显然需要用到__int64,暴力解决是不可能的。由于在poj做了一道求小于n且与n互质的数的和,所以可以直接总和减一下就行了。
设小于N且与N互质的正整数之和, 设为ans. 
不妨设这些数为a[0],a[1], a[2], ..., a[ phi(N)-1 ], 
由gcd(N, a[i]) =1,那么gcd(N,N - a[i]) =1 
这样, N - a[0], N - a[1], ..., N - a[ phi(N)-1]与原数列相同, 从而:  
ans = a[0] + a[1] + ... + a[ phi(N) -1]  
ans= (N - a[0]) + (N - a[1]) + ... + (N - a[ phi[N]-1 ]);两式相加得 ans=N*phi[N]/2; //那么结果就显然了res=(N-1)*N/2-ans; 
 
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
using namespace std;

#define MOD  1000000007; 

__int64 euler_phi(__int64 n)
{
    int m = floor(sqrt(n+0.5));
    __int64 ans = n;
    for(int i = 2; i <= m; i++) if(n%i == 0)
    {
        ans = ans / i * (i-1);
        while(n%i == 0)
        {
            n /= i;
        }
    }
    if(n > 1) ans = ans / n * (n-1);
    return ans;
}


int main()
{
    __int64 n, dif;
    while(~scanf("%I64d", &n), n)
    {
        dif = ((n*(n-1)-n*euler_phi(n))/2)%MOD;
        while(dif < 0) dif += MOD;
        printf("%I64d\n", dif);
    }
    return 0;

} 

 

posted on 2012-08-24 17:26  有间博客  阅读(460)  评论(0编辑  收藏  举报