B - Relatives
https://vjudge.net/contest/240973#problem/B
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
分析:
用歐拉函數做。對於正整數n,歐拉函數可以求出在小於等於n的數中與n互質的數的個數。
歐拉函數:φ(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本身)。 (注意:每種質因數只一個。比如12=2*2*3
那麼φ(12)=12*(1-1/2)*(1-1/3)=4)
代碼:
/*
題目描述:n,一個正數,有多少個小於n且與n互質的數?
兩個數a,b互質僅當不存在x>1,y>0,z>0滿足a=xy且b=xz
Input
多組測試案例。對每一組,標準輸入包含一行:n<=1e9
0代表結束
Output
輸出只有一行,爲問題的答案
思路:
求出n因子的個數x,用n減去x即爲所求
但是如何求n因子的個數呢?
思路好像出現錯誤,是用因數知識加上歐拉函數做
*/
#include <stdio.h>
#include <math.h>
int f(long n)
{
long res=n,x=n,i,z=sqrt(n);
for(i=2;i<=z;i++)
{
if(x%i==0)
res=res/i*(i-1);//爲什麼是先除後乘而先乘後除就不對,公式明明沒有規定順序,而且先乘後除貌似合理一些啊
while(x%i==0)
x=x/i;
}
if(x>1)
res=res/x*(x-1);
return res;
}
int main()
{
long n;
while(~scanf("%ld",&n)&&n)
{
printf("%ld\n",f(n));
}
return 0;
}