POJ 2407 素数筛

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
素数筛水题,本题我用的是一种据说挺厉害的素数筛,特写个博客记录下来,下附ac代码:
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
using namespace std;
int pri[400100];
int p[400000];
void prime()
{
    memset(pri,0,sizeof(pri));
    pri[0]=pri[1]=1;
    int num=0,i,j;
    for(i = 2; i < 400100; ++i)
    {
        if(!(pri[i])) p[num++] = i;
        for(j = 0; (j<num && i*p[j]<400100); ++j)
        {
            pri[i*p[j]] = 1;
            if(!(i%p[j])) break;
        }
    }
}
int power(int x,int y)
{
    int mi=1;
    for(int i=1;i<=y;i++)
    {
        mi*=x;
    }
    return mi-mi/x;
}
int main()
{
    int n;
    prime();
    while(scanf("%d",&n),n)
    {
        int temp=n,sum=1,ok=0;
        for(int i=0;i<400000;i++)
        {
            if(temp%p[i]==0)
            {
                int tot=0;
                while(temp%p[i]==0)
                {
                    tot++;
                    temp/=p[i];
                }
                sum*=power(p[i],tot);
            }
            else if(sum==0&&p[i]>=(int)(sqrt(n)+1))
            {
                printf("%d
",n-1);
                break;
            }
            else if(temp==1)
            {
                ok=1;break;
            }
        }
        if(ok)printf("%d
",sum);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lthb/p/4375021.html