POJ2407-Relatives-欧拉函数

时间:2024-01-05 13:40:38

欧拉函数:

对正整数n,欧拉函数是少于或等于n的数中与n互质的数的数目。

对于一个正整数N的素数幂分解N=P1^q1*P2^q2*...*Pn^qn.

Euler函数表达通式:euler(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…(1-1/pn),或者φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),

其中p1,p2……pn为x的所有素因数,x是不为0的整数。

euler(1)=1(唯一和1互质的数就是1本身)。 
欧拉公式的延伸:

1.小于或等于n的数中,与n互质的数的总和为:φ(n) * n / 2  (n>1)。

2.n=∑d|nφ(d),即n的因数(包括1和它自己)的欧拉函数之和等于n。

代码:

ll euler(ll n){                                   
    ll ans=n;
    for(int i=;i*i<=n;i++){                     //这里i*i只是为了减少运算次数,直接i<=n也没错,
        if(n%i==){                              //因为只有素因子才会加入公式运算。仔细想一下可以明白i*i的用意。
            ans=ans/i*(i-);
            while(n%i==)
                n/=i;                            //去掉倍数
        }
    }
    if(n>)
        ans=ans/n*(n-);
    return ans;
}

举个例子:10

10的质因子为1,2,5;10的欧拉函数是1,3,7,9;i=2;2*2<10;10%2==0;ans=10/2*(2-1)=5;n=10/2=5;

i=3;3*3<10;10%3!=0跳出循环,执行下面的。此时n=5>1;ans=5/5*(5-1)=4;

欧拉函数就是通过质因子找到少于或等于n的数中与n互质的数的数目。具体公式怎么得出来的我也不会,要找本数论好好看看了。

自己再好好想想。看了两三天了,终于知道什么是欧拉函数了

POJ2407

                                                                                 Relatives
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14285   Accepted: 7133

Description

Given n, a positive integer, how many positive integers less than n are relatively prime to n? Two integers a and b are relatively prime if there are no integers x > 1, y > 0, z > 0 such that a = xy and b = xz.

Input

There are several test cases. For each test case, standard input contains a line with n <= 1,000,000,000. A line containing 0 follows the last case.

Output

For each test case there should be single line of output answering the question posed above.

Sample Input

7
12
0

Sample Output

6
4 代码:
#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
ll euler(ll n){
ll ans=n;
for(int i=;i*i<=n;i++){
if(n%i==){
ans=ans/i*(i-);
while(n%i==)
n/=i;
}
}
if(n>)
ans=ans/n*(n-);
return ans;
}
int main(){
ll n;
while(~scanf("%lld",&n)){
if(n==)break;
euler(n);
printf("%lld\n",euler(n));
}
return ;
}

提交n次都是错,原因在于提交的时候没有看清类型,G++才对,GCC交了5次。。。
智障。。。