The number of regular irreducible fractions (with denominator ) is equal to the number of positive integers such that p < n and is coprime with . The count of such numbers equals the Euler function .
Consider the set of all proper fractions with denominator :
After reducing the fractions to their lowest terms, we obtain:
Now, let us group these fractions according to their denominators:
Among these denominators, every divisor of occurs, together with all numerators that are relatively prime to . In other words, for each divisor of , there are exactly irreducible fractions with denominator .
Since every fraction from the original set appears exactly once after reduction, we have:
More generally, if we start with the sequence of proper fractions
and reduce each fraction to its lowest terms, we obtain the following identity:
Example
For n = 12 we have \varphi(12) = 4 regular irreducible fractions:
Algorithm implementation
The euler function computes the value of .
int euler(int n)
{
int i, result = n;
for (i = 2; i * i <= n; i++)
{
if (n % i == 0) result -= result / i;
while (n % i == 0) n /= i;
}
if (n > 1) result -= result / n;
return result;
}The main part of the program. Read the input value of and print .
while(scanf("%d",&n),n)
printf("%d\n",euler(n));Java implementation
import java.util.Scanner;
public class Main
{
static int euler(int n)
{
int result = n;
for(int i = 2; i * i <= n;i++)
{
if (n % i == 0) result -= result / i;
while (n % i == 0) n /= i;
}
if (n > 1) result -= result / n;
return result;
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
while(con.hasNext())
{
int n = con.nextInt();
if (n == 0) break;
System.out.println(euler(n));
}
con.close();
}
}Python implementation
import mathThe euler function computes the value of .
def euler(n):
result = n
i = 2
while i <= math.isqrt(n):
if n % i == 0:
result -= result // i
while n % i == 0: n //= i
i += 1
if n > 1: result -= result // n
return resultThe main part of the program. Read the input value of and print .
while True:
n = int(input())
if n == 0: break
print(euler(n))