You are on page 1of 1

5.3.

NUMBER THEORY 
c Steven & Felix, NUS

In fact, there are only 12 integers less than equal to 36 that are relatively prime to 36. They
are 1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, and 35. As we need to factor N , the complexity of
this algorithm is similar with the complexity of factoring an integer with trial division mentioned
earlier. The code is below.

int EulerPhi(int N) {
vi factors = primeFactors(N);
vi::iterator new_end = unique(factors.begin(), factors.end()); // get unique
int result = N;
for (vi::iterator i = factors.begin(); i != new_end; i++)
result = result - result / *i;
return result;
}

Programming Exercises related to Euler’s Totient (Phi) Function:

1. UVa 10179 - Irreducible Basic Fractions (direct application of Euler’s Phi function)
2. UVa 10299 - Relatives (another direct application of Euler’s Phi function)
3. UVa 10820 - Send A Table (a[i] = a[i - 1] + 2 ×ϕ(i))
4. UVa 11064 - Number Theory
5. UVa 11327 - Enumerating Rational Numbers

5.3.4 Extended Euclid: Solving Linear Diophantine Equation


Motivating problem: Suppose a housewife buys apples and oranges at a total cost of 8.39 SGD. If
an apple is 25 cents and an orange is 18 cents, how many of each type of fruit does she buys?
This problem can be modeled as a linear equation with two variables: 25x + 18y = 839. Since
we know that both x and y must be integers, this linear equation is called the Linear Diophantine
Equation. We can solve Linear Diophantine Equation with two variables even if we only have one
equation! This is different from System of Linear Equations discussed later in Section 5.5.5. The
solution for the Linear Diophantine Equation is as follow [20].
Let a and b be integers with d = gcd(a, b). The equation ax + by = c has no integral solutions
if d | c is not true. But if d | c, then there are infinitely many integral solutions. The first solution
(x0 , y0 ) can be found using the Extended Euclid algorithm shown below (also see [4], Chapter 31),
and the rest can be derived from x = x0 + (b/d)n, y = y0 − (a/d)n, where n is an integer.

// store x, y, and d as global variables


void extendedEuclid(int a, int b) {
if (b == 0) { x = 1; y = 0; d = a; return; }
extendedEuclid(b, a % b);
int x1 = y;
int y1 = x - (a / b) * y;
x = x1;
y = y1;
}

99

You might also like