POJ 2407 Relatives

Relatives
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8923   Accepted: 4184

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

Source

//欧拉函数、求比n小,与n互质的数的个数。
//貌似筛选法也可以求、估计速度没用公式来的快

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string.h>
#define N 100000
using namespace std;
bool hash[N];
bool is_p(int &n)
{
    if(n%2==0) return false;
    int i,m=sqrt(double(n));
    for(i=3;i<=m;i+=2)
     if(n%i==0)
       return false;
    return true;
}
int rc[10000],l;
void set()
{
     int i,j;
    for(i=4;i<N;i+=2)
      hash[i]=1;
    for(i=3;i<N;i+=2)
       if(is_p(i))
         for(j=i+i;j<N;j+=i)
           hash[j]=1;
    j=0;
    for(i=2;i<N;i++)
     if(!hash[i])
      rc[j++]=i;
    l=j;
}
int main()
{
    set();
    int n,i;
    double s;
    bool b;
    while(scanf("%d",&n),n)
    {
        s=n;i=0;
        while(n!=1)
        {    b=0;
            if(is_p(n)){s=s*(1.0-1.0/n);break;}
            while(n%rc[i]==0)
            {
                b=1;
                n=n/rc[i];
            }
            if(b) {s*=(1.0-1.0/rc[i]);}
            i++;
        }
       n=s+0.5;
       printf("%d\n",n);
    }
    return 0;
}

你可能感兴趣的:(relative)