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 13 24 25 46 27 68 49 610 411 1012 413 12我一开始的想法很简单,用辗转相除法求最大公因数
当然是可以accept#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; }
今天我觉得我这样是不是太简单了,于是去搜了以下,发现好多人都是利用欧拉函数 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; }