(欧拉公式 很水) Coprimes -- sgu -- 1002

链接:

http://vj.acmclub.cn/contest/view.action?cid=168#problem/B

 Coprimes

时限:250MS     内存:4096KB     64位IO格式:%I64d & %I64u

问题描述

 

For given integer N (1<=N<=104) find amount of positive numbers not greater than N that coprime with N. Let us call two positive integers (say, A and B, for example) coprime if (and only if) their greatest common divisor is 1. (i.e. A and B are coprime iff gcd(A,B) = 1).

 

Input

Input file contains integer N.

 

Output

Write answer in output file.

 

Sample Input

9

Sample Output

6

初等数论里的欧拉公式:

  欧拉φ函数:φ(n)是所有小于n的正整数里,和n互素的整数的个数。n是一个正整数。

  欧拉证明了下面这个式子:

  如果n的标准素因子分解式是p1^a1*p2^a2*……*pm^am,其中众pj(j=1,2,……,m)都是素数,而且两两不等。则有

  φ(n)=n(1-1/p1)(1-1/p2)……(1-1/pm)

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>

using namespace std;

#define INF 0x3f3f3f3f
#define N 11000

int a[N], vis[N], cnt;

void IN()
{
    int i, j;
    cnt = 0;

    memset(a, 0, sizeof(a));
    memset(vis, 0, sizeof(vis));

    for(i=2; i<N; i++)
    {
        if(!vis[i])
        {
            a[cnt++] = i;
            for(j=i+i; j<N; j+=i)
                vis[j] = 1;
        }
    }
}

int main()
{
    int n;

    IN();

    while(scanf("%d", &n)!=EOF)
    {
        int i=0, aa[N]={0}, bnt = 1, m;

        m = n;
        while(a[i]<=m)
        {
            if(m%a[i]==0)
            {
                 m /= a[i];
                 if(a[i]!=aa[bnt-1])
                 aa[bnt++] = a[i];
            }
            else
                i++;
        }

        for(i=1; i<bnt; i++)
            n = n-n/aa[i];

        printf("%d
", n);
    }

    return 0;
}

我醉了,其实可以这么简单

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>

using namespace std;

#define INF 0x3f3f3f3f
#define N 11000

int gcd(int a, int b)
{
    return b==0?a:gcd(b, a%b);
}

int main()
{
    int n;

    while(scanf("%d", &n)!=EOF)
    {
        int sum = 0;
        for(int i=1; i<=n; i++)
        {
            if(gcd(i, n)==1)
                sum ++;
        }
        printf("%d
", sum);
    }

    return 0;
}
勿忘初心
原文地址:https://www.cnblogs.com/YY56/p/4803090.html