Poj(2407),Greater New York Regional 2015 (D)

题目链接:http://poj.org/problem?id=2407

Relatives
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 13599   Accepted: 6772

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

 
两道题差不多的结题思路,都是求一个数的互质的数的个数。用欧拉函数。
欧拉函数:
一个数x的素因数p1,p2,p3,......,那么他的欧拉函数就为x(1-1/p1)(1-1/p2)(1-1/p3)......
欧拉函数相当于一个筛选,找到一个素因数后,就将该素因子全部约掉。
然后Greater New York Regional 2015 (D)中,1是一个特例,他有0/1,1/1两个互质的数,所以ans[1] = 2;
然后再打表就可以了。
#include <stdio.h>

int Euler(int n)
{
    int ans = n;
    for(int i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            n/=i;
            ans = ans - ans/i;

            while(n%i==0)
            {
                n/=i;
            }

        }
    }
    if(n>1) ans = ans - ans/n;
    return ans;
}

int main()
{
    int n;
    while(scanf("%d",&n),n)
    {
        printf("%d
",Euler(n));
    }
    return 0;
}
View Code
#include <stdio.h>


int Euler(int n)
{
    int res = n;
    for(int i=2; i*i<=n; i++)
    {
        if(n%i==0)
        {
            n=n/i;
            res = res - res/i;
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1) res = res - res/n;
    return res;
}

int main()
{
    int cases;
    scanf("%d",&cases);

    int ans[10005];
    ans[1] = 2;
    for(int i=2; i<=10000; i++)
    {
        ans[i]=ans[i-1]+Euler(i);
    }
    while(cases--)
    {
        int t,k;
        scanf("%d%d",&t,&k);
        printf("%d %d
",t,ans[k]);
    }
    return 0;
}
View Code
 
原文地址:https://www.cnblogs.com/TreeDream/p/5781830.html