sgu102-欧拉函数

102. Coprimes

time limit per test: 0.25 sec. 
memory limit per test: 4096 KB

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互质的个数
 
 
2 1
3 2
4 2
5 4
6 2
7 6
8 4
9 6
10 4
11 10
12 4
13 12
我一开始的想法很简单,用辗转相除法求最大公因数
#include <iostream>
using namespace std;

unsigned int gcd(unsigned int a,unsigned int b)
{
	int r;
	while(b>0)
	{
		r=a%b;
		a=b;
		b=r;
	}
	return a;
}

int main()
{
	unsigned int N;
	cin >> N;
	unsigned int r = 1;
	for(int i = 2;i < N;i++){
		if(gcd(N,i) == 1){
			r++;
		}
	}
	cout << r;
	return 0;
}
当然是可以accept
 
今天我觉得我这样是不是太简单了,于是去搜了以下,发现好多人都是利用欧拉函数 0 0
数论,对正整数n,欧拉函数是少于或等于n的数中与n互质的数的数目。例如φ(8)=4,因为1,3,5,7均和8互质
φ函数的值  通式:φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),其中p1, p2……pn为x的所有质因数,x是不为0的整数。φ(1)=1(唯一和1互质的数(小于等于1)就是1本身)。 (注意:每种质因数只一个。比如12=2*2*3那么φ(12)=12*(1-1/2)*(1-1/3)=4
这不正是我们要求的么
 
#include<cstdio>
int main()
{
    int n = 0;
    scanf("%d",&n);

    int p=2,ans=n;
    while(n!=1)
    {
		if(n%p==0) 
        {
        	ans=ans*(p-1)/p;
        	while(n%p==0) n/=p;
        }
        p++;
    }
    printf("%d",ans);
    return 0;
}


 

                
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值