Franco Vivaldi (Author) - Experimental Mathematics With Maple-Chapman and Hall - CRC (2001)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 236

Experimental

Mathematics
with
MAPLE
CHAPMAN & HALL/CRC MATHEMATICS

OTHER CHAPMAN & HALL/CRC MATHEMATICS TEXTS:

Functions of Two Variables, Algebraic Combinatorics


Second edition C. D. Godsil
S. Dineen
An Introduction to Abstract
Network Optimization Analysis-PB
V. K. Balakrishnan W. A. Light

Sets, Functions and Logic: The Dynamic Cosmos


A foundation course in mathematics M. Madsen
Second edition
K. Devlin Algorithms for Approximation II
J. C. Mason and M. G. Cox
Algebraic Numbers and Algebraic
Functions Introduction to Combinatorics
P. M. Cohn A. Slomson

Dynamical Systems: Galois Theory


Differential equations, maps and I. N. Stewart
chaotic behaviour
D. K. Arrowsmith and C. M. Place Elements of Algebraic Coding
Theory
Control and Optimization L. R. Vermani
B. D. Craven
Linear Algebra:
Elements of Linear Algebra A geometric approach
P. M. Cohn E. Sernesi

Error-Correcting Codes A Concise Introduction to


D. J. Bayliss Pure Mathematics
M. W. Liebeck
Introduction to Calculus of
Variations Geometry of Curves
U-Brechtken-Mandershneid J. W. Rutter

Integration Theory
W. Filter and K. Weber

Full information on the complete range of Chapman & Hall/CRC Mathematics books is
available from the publishers.
Experimental
Mathematics
with
MAPLE
Franco Vivaldi

Boca Raton London New York

CRC Press is an imprint of the


Taylor & Francis Group, an informa business
A CHAPMAN & HALL BOOK
disclaimer Page 1 Monday, January 8, 2001 2:13 PM

CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742

First issued in hardback 2017

© 2001 by Taylor & Francis Group, LLC


CRC Press is an imprint of Taylor & Francis Group, an Informa business

ISBN 13: 978-1-138-41196-8 (hbk)


ISBN 13: 978-1-58488-233-6 (pbk)

Library of Congress Cataloging-in-Publication Data

Vivaldi, Franco
Experimental mathematics with Maple / Franco Vivaldi.
p. cm. — (Chapman & Hall/CRC mathematics)
Includes bibliographical references and index.
ISBN 1-58488-233-6 (alk. paper)
1. Mathematics—Data processing. 2. Maple (Computer file) I. Title.
II. Series.
QA76.95 .V58 2001
510—dc21 00-052372

This book contains information obtained from authentic and highly regarded sources. Reprinted material
is quoted with permission, and sources are indicated. A wide variety of references are listed. Reasonable
efforts have been made to publish reliable data and information, but the author and the publisher cannot
assume responsibility for the validity of all materials or for the consequences of their use.

Neither this book nor any part may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, microfilming, and recording, or by any information storage or
retrieval system, without prior permission in writing from the publisher.

The consent of CRC Press LLC does not extend to copying for general distribution, for promotion, for
creating new works, or for resale. Specific permission must be obtained in writing from CRC Press LLC
for such copying.

Direct all inquiries to CRC Press LLC, 2000 N.W. Corporate Blvd., Boca Raton, Florida 33431.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are
used only for identification and explanation, without intent to infringe.

Visit the CRC Press Web site at www.crcpress.com

No claim to original U.S. Government works


Library of Congress Card Number 00-052372
A Chiara e Giulia,
per l'allegria.
Contents
1 What is Maple? 1
2 Integers and rationals 5
2.1 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Arithmetical expressions . . . . . . . . . . . . . . . . . . . . 8
2.3 Some Maple . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.4 Divisibility . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.5 Rationals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6 Primes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.7 Standard library functions . . . . . . . . . . . . . . . . . . . 37

3 Sets and functions 39


3.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.2 Sets with Maple . . . . . . . . . . . . . . . . . . . . . . . . 45
3.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.4 User-de ned functions . . . . . . . . . . . . . . . . . . . . . 50

4 Sequences 59
4.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.2 Sequences with Maple . . . . . . . . . . . . . . . . . . . . . 61
4.3 Plotting the elements of a sequence . . . . . . . . . . . . . . 64
4.4 Periodic and eventually periodic sequences . . . . . . . . . . 67
4.5 Some non-periodic sequences . . . . . . . . . . . . . . . . . 70
4.6 Basic counting sequences . . . . . . . . . . . . . . . . . . . . 77
4.7 Sequences de ned recursively . . . . . . . . . . . . . . . . . 82

5 Real and complex numbers 89


5.1 Digits of rationals . . . . . . . . . . . . . . . . . . . . . . . . 89
5.2 Real numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 96
5.3 Random and pseudo-random digits . . . . . . . . . . . . . 99
5.4 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . 102
5.5 Standard library functions . . . . . . . . . . . . . . . . . . . 108

vii
viii

6 Structure of expressions 113


6.1 Analysis of an expression . . . . . . . . . . . . . . . . . . . 113
6.2 More on substitutions . . . . . . . . . . . . . . . . . . . . . 117
6.3 Functions acting on operands of expressions . . . . . . . . . 119
7 Polynomials and rational functions 127
7.1 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
7.2 Polynomial arithmetic . . . . . . . . . . . . . . . . . . . . . 128
7.3 Rational functions . . . . . . . . . . . . . . . . . . . . . . . 138
7.4 Basic manipulations . . . . . . . . . . . . . . . . . . . . . . 139
7.5 Partial fractions decomposition . . . . . . . . . . . . . . . 142
8 Finite sums and products 147
8.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
8.2 Sums and products with Maple . . . . . . . . . . . . . . . . 149
8.3 Symbolic evaluation of sums and products . . . . . . . . . . 152
8.4 Double sums and products . . . . . . . . . . . . . . . . . . . 154
8.5 Sums and products as recursive sequences . . . . . . . . . . 160
9 Elements of programming 163
9.1 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
9.2 Study of an eventually periodic sequence . . . . . . . . . . . 173
9.3 Conditional execution . . . . . . . . . . . . . . . . . . . . . 177
9.4 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
10 Vector spaces 185
10.1 Cartesian product of sets . . . . . . . . . . . . . . . . . . . 185
10.2 Vector spaces . . . . . . . . . . . . . . . . . . . . . . . . . . 186
10.3 Vectors with Maple . . . . . . . . . . . . . . . . . . . . . . . 188
10.4 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
10.5 Matrices with Maple . . . . . . . . . . . . . . . . . . . . . . 192
11 Modular arithmetic 201
11.1 A modular system . . . . . . . . . . . . . . . . . . . . . . . 201
11.2 Arithmetic of equivalence classes . . . . . . . . . . . . . . . 204
11.3 Some arithmetical constructions in F p . . . . . . . . . . . . 206
12 Some abstract structures 213
12.1 The axioms of arithmetic . . . . . . . . . . . . . . . . . . . 213
12.2 Metric spaces . . . . . . . . . . . . . . . . . . . . . . . . . . 214
12.3 Rings and elds . . . . . . . . . . . . . . . . . . . . . . . . . 214
12.4 Vector spaces . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Preface
This text contains suÆcient material for a one-semester course in exper-
imental mathematics for rst-year students in mathematics or computer
science. The course | based on the computer algebra system Maple1 |
introduces the foundations of discrete mathematics while developing basic
computational skills. No previous knowledge of computing is assumed.
Contrary to common folklore, mathematical knowledge is seldom ac-
quired through a sequence of awless logical steps within an abstract frame-
work. A mathematical discovery is more likely to originate from the pa-
tiently collected experience of many speci c computations. With the aid
of computers, contemporary mathematics is beginning to recover the cul-
tural unity that had characterized its tradition until the beginning of the
19th-century, when the boundaries between the pure and the applied side
of the discipline were blurred, and when even the greatest minds felt lit-
tle obligation to hide their calculations and experiments behind a polished
axiomatic presentation.
It is in this spirit that we intend to present mathematics to beginning
undergraduates. Students often arrive at university without a background
in abstract reasoning, and with only a limited experience in the mechanical
application of techniques. Developing understanding and familiarity with
basic abstract concepts, notation, and jargon (sets, functions, equivalence
classes, etc.) is already a considerable task. In order to acquire a taste
for abstraction, the students rst need to gather evidence of mathematical
phenomena.
Following an emerging trend in research, we shall place abstraction and
axiomatization at the end of a learning process that begins with computer
experimentation. Our strategy is to expose the students to a large num-
ber of concrete computational examples, repeatedly encouraging them to
isolate the general from the particular, to explore, to make a synthesis of
computational results, to formulate conjectures, and to attempt rigorous
proofs whenever possible.
The choice of an algebraic manipulator | as opposed to a compiled
1 TM
Maple is a registered trademark of Waterloo Maple, Inc. 57 Erb St. W., Waterloo,
Canada N2L 6C2, www.maplesoft.com.

ix
x

language | is central to this strategy, as it allows a straightforward repre-


sentation of many mathematical objects (such as numbers, sets, polynomi-
als, functions, etc.), thereby eliminating layers of technicalities that, with
a compiled language, would invariably lie between the user and the object
being represented.
Throughout the course, arithmetic takes centre stage. Arithmetical con-
cepts are transparent and tangible, and possess an appeal to fundamentals
seldom found in undergraduate mathematics. Experimentation in arith-
metic can be at the same time accessible, illuminating, and rewarding, and
Maple's remarkable possibilities will not fail to impress the student.
The arithmetic of integers and rationals is developed in some detail.
The real numbers are introduced constructively, from the analysis of the
digits of the rationals. Other examples of arithmetical environments include
polynomials, rational functions, vector spaces, and modular integers. Some
of this material may be treated as optional. (An introductory text, see
Reference [3], could provide complementary material and support on the
theoretical aspects of this course.)
A second unifying theme is that of a sequence. Sequences are rst
introduced as explicit functions of the integers. For their Maple represen-
tation, we rely on the arrow operator construct -> (functions de ned by a
single statement), which closely mimics the mathematical notation. Recur-
sive sequences appear later, and are characterized from the perspective of
the theory of dynamical systems. They provide examples of complicated
phenomena from simple ingredients | an ideal environment for experimen-
tation.
The elements of programming are introduced gradually. Iteration (the
do-structure) is delayed until the second part of the course, to allow the
concept and notation of a sequence to consolidate. Conditional execution
(the if-structure) is introduced and used extensively to de ne characteristic
functions, thereby providing the necessary exposure to logical calculus. Its
general form and usage are discussed only towards the end of the course, as
optional material. The de nition of procedures is also included as optional
material. In our view, procedures could be omitted altogether from a rst
course in computing. In their place, we make extensive use of the arrow
operator (one-statement procedures), as well as of structural functions such
as seq, map, and select.
Few theorems are stated, often without proof but always exempli ed
by computations. Several examples of abstract structures (metric spaces,
rings, elds, etc.) are given. The corresponding axiomatic de nitions are
collected together in the last chapter, as a summary of the theory under-
pinning the course.
Computer work is essential. Many problems are provided, with the
more diÆcult ones agged by a star. The student is expected to attempt
at least half of them. The un-starred problems, particularly those in the
xi

later chapters, are meant to have a degree of diÆculty comparable to that


of examination questions.
Starred chapters, sections, examples, etc., contain optional material,
which may require support from other courses, particularly linear algebra.
In this course, Maple is viewed more as a tool than as an object of
study in itself. Nevertheless, the material presented here constitutes a
fairly exhaustive introduction to the language.

This material has grown from a beginning undergraduate course I have


taught at the University of London for ve years. I would like to thank all
the students who participated in the `Spot the error' competition, provid-
ing minute inspections of early versions of the manuscript in the hope of
winning tickets for some hot West End show. I am also grateful to Sheryl
Koral, Leonard Soicher, and Francis Wright, who carefully read various
parts of the manuscript at various stages and o ered invaluable comments
and suggestions. It is now up to the reader to spot the remaining errors
(see the book's web page, below).

London Franco Vivaldi

Supplementary material, comments, and errata


can be found on the book's web page:
http://www.maths.qmw.ac.uk/~fv/emm/
Chapter 1

What is Maple?
Maple is a powerful system for symbolic computation. In this chapter, we
intend to give you a avour of Maple's capabilities by taking you through
a guided tour of some Maple commands. You need a computer with a
working copy of Maple software.
Starting and ending a Maple session
The procedure for starting a Maple session depends on the computer and
on the details of the software installation. For instance, if you are using a
window-based version of the software, you will click on Maple's icon with
the mouse. After starting a Maple session, the system will greet you with
a prompt, which may look like this
>
The cursor | the symbol that indicates the place where any typing will
end up (typically a bar `|' or an underscore ` ') | will be positioned just
after the cursor, waiting for input. Whenever Maple displays a prompt, it
means that it is ready to accept a new command. One of these commands
is quit (or done, or stop), which terminates a Maple session.
> quit
You rst type it, then press the RETURN key. In a window environment,
you may achieve the same result by clicking on the `quit' button with the
mouse. Before falling silent, Maple will display a brief summary of the
resources used during the session, which need not concern you now.
A guided tour of Maple
Here are a few things Maple can do.
Let n be equal to 40! (read `40 factorial'), which is the product of the
rst 40 positive integers: 40! = 1  2  3    39  40:
> n:=40!;

n := 815915283247897734345611269596115894272000000000

1
2 CHAPTER 1. WHAT IS MAPLE?
Decompose n into prime factors.
> ifactor(n);

(2) (3) (5) (7) (11) (13) (17) (19) (23) (29) (31) (37)
38 18 9 5 3 3 2 2 2

(Did you expect 40! to be so large? Does its prime factorization make sense
to you? Think about it.)
Display the rst 100 digits of . (Note that Pi has upper-case P and
lower-case i.)
> evalf(Pi,100);

3:141592653589793238462643383279502884197169399375105n
820974944592307816406286208998628034825342117068
Expand the binomial (x + py) : 10

> expand((x+sqrt(y))^10);
p
x10 + 10 x9 y + 45 x8 y + 120 x7 y 3=2 + 210 x6 y 2 + 252 x5 y 5=2
+210 x4y3 + 120 x3y7=2 + 45 x2y4 + 10 xy9=2 + y5
Compute the nite sum
n
X1
k 3 5k :
k=1

> sum(k^3*5^k,k=1..n-1);
45 5n n 115 5n 15 5nn + 1 n 5n + 115 2 3
32 128 16 4 128
Compute the limit
lim 3x 1 :
x!1 x arctan(x) + ln(x)

> limit((3*x-1)/(x*arctan(x)+ln(x)),x=infinity);
6 1

Compute the derivative of sin x ln(1 2
x3 ) .
> diff(sin(x^2*ln(1-x^3)),x);
 
31 xx
4
cos(x ln(1
2
x3 )) 2 x ln(1 x3 ) 3

Compute the inde nite integral


Z p
x2 x2 a2 dx:
3

> int(x^2*sqrt(x^2-a^2), x);


1 x x a  = + 1 a xpx a 1 a ln(x + px a )
2 2 3 2 2 4
4 8 8
2 2 2 2

Solve the system of linear equations


5x 3y = 2z + 1; x + 4y = 7z; 3x + 5y = z:

> eqns:=f5*x-3*y=2*z+1,-x+4*y=7*z,3*x+5*y=zg;
eqns := f5x 3y = 2z + 1; x + 4y = 7z; 3x + 5y = z g
> solve(eqns,fx,y,zg);

x=
31 ; y = 22 ; z = 1 
255 255 15
Plot the graph of the function
sin(x ) ln(1 + x );
3 2
x 2 [ 2; 2]:
> plot(sin(x^3)*log(1+x^2), x=-2..2);

1.5

0.5

-2 -1 0 1 2
x

-0.5

-1

-1.5
Chapter 2

Integers and rationals


This chapter is devoted to the arithmetic of integers and rationals. At the
start, we use Maple just as a calculator. The basic elements of the language
are introduced as they become necessary to illustrate arithmetical concepts.
2.1 Integers

The building blocks of arithmetic are the natural numbers, which form a
set denoted by N
N = f0; 1; 2; 3; : : : g:
The notion of a set | a collection of distinct objects | is fundamental in
mathematics. It will be dealt with in some detail in later chapters. Here
it suÆces to say that the objects constituting the set N are the integer
zero and the positive integers, which should be familiar to everyone. These
elements are listed within curly brackets, separated by commas. As we
cannot list them all, we resort to dots.
0 1 2 3
    :::

Figure 2.1: Graphical representation of the set N of natural numbers, as


evenly spaced points on a semi-in nite line.
To say that an integer n belongs to N, or is an element of N, we use the
symbol 2. Its negation is 62. Thus,
23 2 N 1 62 N:
The symbol N will be used to denote the set of positive integers
+

N = f1; 2; 3; : : : g:
+

5
6 CHAPTER 2. INTEGERS AND RATIONALS
As an arithmetical environment, the set N is plainly inadequate. For
instance, 2 and 3 belong to N, and so do their sum 2 + 3 = 5 and product
2  3 = 6. But their di erence 2 3 = 1 does not. One says that N is
not closed under subtraction, that is, subtraction may take you out of the
set. The lack of closure under subtraction | a serious problem | can be
stated without ever mentioning the word `subtraction' or introducing the
minus sign. It suÆces to note that the equation
x+a = b a; b 2 N (2.1)
cannot always be solved for x in N. This formulation is useful, because it
only makes use of minimal ingredients: the set N and an operation, called
addition, that allows us to combine its elements together.
To solve this problem, we adjoin to N the negative integers, to obtain
the set Z of all integers
Z = f: : : ; 2; 1; 0; 1; 2; : : :g:

2 1 0 1 2
::: Æ Æ    :::

Figure 2.2: The set Z, represented as points on a line. The white circles
denote elements of Z which are not in N.
Note that the elements of Z originate precisely from the distinct solu-
tions x of equation (2.1). For instance, by setting b = 0 in (2.1) and letting
a vary among all positive integers, we obtain all the negative integers. Like-
wise, by setting a = 0 and letting b vary in N, we recover all elements of N.
It follows that every element of N is also an element of Z, which we express
by saying that N is contained in Z (or that N is a subset of Z) and write
N  Z: (2.2)
This is called an inclusion relation. By the same token, N  N.
+

The sum, di erence, and product of any two elements of Z yield another
element of Z, and for this reason the arithmetic in Z is simpler than that
in N. In other words, each of the following equations
x =a+b x+a=b x = a  b; a; b 2 Z (2.3)
can be solved by some x 2 Z. There is still a problem, though: the integers
are not closed under division | the equation x  a = b cannot be added to
the list (2.3). Indeed, 2 and 3 are integers, but 2=3 is not. This problem
will lead to the introduction of the rational numbers.
Apart from the existence of arithmetical operations, two important
structures are de ned in Z which justify the representation of the integers
2.1. INTEGERS 7
as equally spaced points on a line, as in gure 2.2. They are an ordering
relation and a distance.
First, the integers are ordered, in the sense that, for any a; b 2 Z, at
least one of the following relations is satis ed:
ab b  a: (2.4)
If both are satis ed, then a = b, while a 6 b is equivalent to a > b, etc.
The reader should be familiar with the following properties of the ordering
relation :
if a  b and b  c then a  c
if a  b then a + c  b + c
if a  b and 0  c then ac  bc:
Second, we can measure the distance between two integers. To do so,
we rst de ne the size of an integer x as the absolute value of x, given by
jxj = x x xx < 00:
n
(2.5)
The quantity jxj is non-negative, and is equal to zero precisely when x = 0.
The numbers x and x have the same absolute value.
The distance between two integers x and y is de ned as the size of the
integer x y, which is jx yj. In particular, jxj = jx 0j is the distance
between x and 0. From the de nition, it follows that (i) the distance
between x and y is the same as that between y and x (since x y and y x
have the same size); (ii) the distance between x and y is zero precisely when
x = y (since x y is equal to zero only in this case); and (iii) the minimal
positive distance between two integers is 1. Moreover, any three integers x,
y , and z satisfy the inequality

jx z j  jx yj + jy z j (2.6)
which is called the triangle inequality. The latter is justi ed by noting
that the direct journey from x to z cannot be longer than that with an
intermediate stop at y.
z y x x z y
(i)    (ii)   
Figure 2.3: The triangle inequality (2.6). (i) The equal sign holds when y
lies between x and z (including the endpoints). (ii) Strict inequality holds
when z is in the middle.
8 CHAPTER 2. INTEGERS AND RATIONALS
2.2 Arithmetical expressions

Arithmetic in Z is straightforward with Maple.


> 5+3;
8
The arithmetical expression 5+3 consists of the arithmetical operator + and
the two operands 5 and 3. Its value is 8. The only syntactical constraint is
the semicolon at the end of the expression, which informs Maple that you
have nished typing in your input. Maple won't work until you put one,
and then press the RETURN key. If you do forget to put the semicolon,
that is, you type
> 5+3
followed by RETURN, then Maple will do nothing. After a while, you'll
begin to suspect that something is wrong, but do not panic, you can add
the semicolon at any time, followed by RETURN. One may perform several
additions at once
> 1+10+100+1000+10000+100000+1000000+10000000;
11111111
What happens if one makes a syntactical error? For instance, the expression
5++3 is illegal
> 5++3;
syntax error: `+` unexpected
When a syntactical error occurs, Maple writes an error message and po-
sitions the cursor immediately before the rst incorrect character. In this
eventuality, just edit the incorrect character. Since Maple diagnoses one
error at a time, clearing all errors in an expression may take several steps.
The characters +, -, *, and / denote the four arithmetical operators:
addition, subtraction, multiplication, and division, respectively. An expres-
sion may contain any number of operators, but this creates a problem of
representation. For instance, the meaning of the Maple expressions 8+4+2
and 8*4*2 is clear. But what does 8/4/2 mean? If we translate it literally
into mathematical notation, we get a rather bizarre result
8
4
2
The ambiguity arises because division | unlike addition and multiplication
| is non-associative: that if a; b, and c are integers, with b and c nonzero,
then (a=b)=c (meaning that a=b is done rst, and then the result is divided
by c) is generally di erent from a=(b=c) (meaning that b=c is done rst, and
then a is divided by it). Thus, (8=4)=2 = 2=2 = 1 while 8=(4=2) = 8=2 = 4.
Note that subtraction su ers from the same problem, while, as we have
2.2. ARITHMETICAL EXPRESSIONS 9
pointed out, addition and multiplication are associative (see section 12.1
for formal de nitions)
(a + b) + c = a + (b + c) (a  b)  c = a  (b  c):
It turns out that Maple always starts from the division on the left
> 8/4/2;
1
and to give priority to the rightmost division, parentheses are needed
> 8/(4/2);
4
The use of parentheses, even when redundant, often clari es the meaning
of an expression, so it is good practice to write (8/4)/2 instead of 8/4/2.
Moreover, when it comes to redundant parentheses, Maple is very tolerant
> (((((8/((((4)))))))))/((2));
1
(Note that only round brackets are allowed: square and curly brackets have
a speci c meaning in Maple, and cannot be used to parenthesise expres-
sions.) Sometimes Maple will insist that parentheses be used, even if the
ambiguity could, in principle, be resolved. For instance, we cannot write
3  ( 2) without parentheses, even though this expression has only one
meaningful interpretation, which yields the value 6. If you type 3*-2 you
get an error termination.
The exponentiation operator is represented by the character `^', that
is, 2^14 means 2 . The exponentiation is non-associative, but unlike for
14

division or subtraction, Maple does require that a chain of exponentials be


fully parenthesised, to resolve any ambiguity
> 2^(2^3);
256
> (2^2)^3;
64
If you type 2^2^3 you get an error termination.
That Maple is no ordinary calculator will become clear as soon as you
try something like this
10 CHAPTER 2. INTEGERS AND RATIONALS
> 2^1279-1;

104079321946643990819252403273640855386152622472667048053191n
12350403608059673360298012239441732324184842421613954281n
00779138356624832346490813990660567732076292412950938922n
03457731833496615835504729594205476898112116936771475484n
78866962501384438260291732348885311160828538416585028255n
60466622483189091880184706822220314052102669843548873295n
8028878050869736186900714720710555703168729087
(2.7)
The integer 21279
1 has 386 decimal digits. (It turns out to be a prime. To
construct even larger primes, see the end of section 2.6). As the result does
not t on a single line, Maple has automatically appended the continuation
character `n ' which indicates that the output continues on the following
line. In principle, we can compute and display extremely large integers, with
up to half a million decimal digits, on most 32-bit computers. In practice,
however, to compute and display very large integers, the computer may
take longer than the maximum time we are prepared to wait (100 years, for
instance). (To nd out the maximum number of decimal digits supported
by your computer, type kernelopts(maxdigits).)
The expression 2^1279-1 contains two distinct arithmetical operators,
exponentiation and subtraction. Again, there are two possibilities, namely
(a) 2 1279
1 (b) 2 1279 1
=2 1278

depending on whether exponentiation (case (a)) or subtraction (case (b)) is


done rst. Because the result was an odd number, we tentatively conclude
that Maple has given priority to exponentiation. But we do not know
Maple's rule yet, since Maple could have given priority to the operator on
the left. To settle the issue we try again
> 3-2^5;
29
No, Maple really executes exponentiation before subtraction; otherwise, we
would have obtained (3 2) = 1 = 1.
5 5

> (3-2)^5;
1
If there is more than one operator, the order of evaluation of an ex-
pression is (i ) exponentiation, followed by (ii ) multiplication or division,
followed by (iii ) addition, subtraction, or negation (changing sign). If more
than one operator with the same priority appears, evaluation proceeds from
left to right for groups (ii ) and (iii ). Chains of exponentiation operators
are illegal, as we have seen. The parentheses `(' and `)' may be used to alter
the order of evaluation and to introduce signed operands. A sub-expression
2.2. ARITHMETICAL EXPRESSIONS 11
enclosed in parentheses is always evaluated rst, and if there is more than
one of them, with left to right priority.
Example 2.1. Let us construct the following expression
2  + 6 = (2  + 6) = ((2  ) + 6) :
34 5 (3 4 5) ((3 4) 5)
(2.8)
78 (7  8) (7  8)
This expression is normally written in the form appearing on the left, with-
out parentheses. Its architecture | a numerator with some material at an
exponent, and a denominator | implies three sets of parentheses (middle
expression), while a further layer of parentheses spells, in detail, the order
of evaluation of all arithmetical operators (rightmost expression).
In all, we have seven operands and six operators, and the order in which
the operations have to be performed is the following ( rst a, then b, etc.)
2 ^3  4 5 + 6 = 7  8
c a b d f e

Accordingly, we build the Maple expressions step by step, as follows:


2 ^ 3 * 4 - 5 + 6 / 7 * 8
2 ^ (3 * 4) - 5 + 6 / 7 * 8
2 ^((3 * 4) - 5) + 6 / 7 * 8
(2 ^((3 * 4) - 5)) + 6 / 7 * 8
((2 ^((3 * 4) - 5)) + 6) / 7 * 8
((2 ^((3 * 4) - 5)) + 6) / (7 * 8)

Thus, the correct expression is ((2^((3*4)-5))+6)/(7*8) (the rightmost


expression in (2.8)). By taking advantage of the order in which Maple per-
forms arithmetical operations, we may simplify it to (2^(3*4-5)+6)/(7*8),
but no further.
Exercises
Exercise 2.1. Construct the following expressions:
1) a
bc
[1] 2) ab + c [1] 3) ab
c
d
[0]

abc d a b a
4) [2] 5) [2] 6) c [1]
e c d b+
d
Try to minimize the use of parentheses by taking advantage of the order of
evaluation of arithmetical operators. The minimal number of parentheses
needed in each case is indicated in square brackets.
12 CHAPTER 2. INTEGERS AND RATIONALS
Exercise 2.2. Evaluate the following arithmetical expressions, trying to
minimize the use of parentheses.
1 1766319049 161  226153980 3 5
3 3  181:
2 2
2 2 3
4 + 17  8
7
5
The symbol `' denotes multiplication. The expression on the left is an
arithmetical miracle. Change just a digit in one of the integers in the
denominator, and compare the result.
2.3 Some Maple

In this section we develop a repertoire of Maple tools.


Basic tricks
Blanks can be inserted freely between operators, operands, and parentheses,
and because a new line character is interpreted as a blank, a command can
be entered on several lines.
> 5
> + 8
>
> ;
13
(This is why Maple does not complain when you forget the semicolon!)
However, blanks are not allowed between the digits of a number, and in
order to break long numbers across several lines of input, one must use the
backslash character `n '
> 1234n
> 56789 + 876543n
> 210;
999999999
Omitting the backslash causes an error termination. For instance, the state-
ments
> 12
> 34+1;
are interpreted as 12 34+1, which is not a valid expression.
The character `%', called a ditto variable, can be used in any expression
to represent the value of the previous expression, that is, the output of the
previous command.
> 51^2+80^2-1;
9000
2.3. SOME MAPLE 13
> %/1000;
9
Here the ditto variable assumes the value of the expression 51^2+80^2-1.
Because it is the value that is substituted, and not the expression itself,
the parentheses are not needed. In other words, the above expression is
equivalent to (51^2+80^2-1)/1000 and not to 51^2+80^2-1/1000 (verify
this).
Maple supports other ditto variables. The variable `%%' assumes the
value of the next-to-last command, and `%%%' assumes the value of the
command before (but four or more percent signs mean nothing). Ditto
variables are very handy when building up complicated expressions, since
the correctness of each sub-expression can be checked separately. In the
following example, we evaluate the expression (12 + 1 ) (10 + 9 ) in
3 3 3 3

three steps
> 12^3+1^3;
1729
> 10^3+9^3;
1729
> %%-%;
0
When a computation involves a sequence of commands, one may wish to
suppress the display of intermediate results. This is done by appending at
the end of the command a colon `:' rather than a semicolon `;'
> 12^3+1^3:
> 10^3+9^3:
> %%-%;
0
Example 2.2. Evaluate the following arithmetical expression
((((1 + 1)  2 + 1)  3 + 1)  4 + 1)  5:
This expression is nested, and it should be built from the inside out
> 1:
> (%+1)*2:
> (%+1)*3:
> (%+1)*4:
> (%+1)*5;
325
14 CHAPTER 2. INTEGERS AND RATIONALS
In Maple, one can place more than one statement on the same line. All
syntactical rules described above apply.
> 1+1:%-2;%%;
0
2
This feature should be used sparingly, because it can lead to illegible codes.
It is also possible to display more than one result on the same line of output,
by separating expressions with commas
> 1+1:%-2,%;
0; 2
The composite expression %-2,% constitutes a single statement (this con-
struct will be considered in greater detail in a later chapter). Compare
carefully the use of ditto variables in the last two examples.
Comments can be inserted in a Maple command using the character #.
Everything after that character is ignored. Comments can also be inserted
in the output, by enclosing them between double quotes.
> "one plus one equals",1+1; # this should be about two
one plus one equals; 2
> # cool!

Variables
Mathematical variables represent `indeterminates' or `unknowns'. So by
(a + b) we denote the square of the sum of two unspeci ed quantities.
2

Maple operates much in the same way


> (a+b)^2;
(a + b)2

We shall still refer to (a + b) as the value of Maple's expression (a+b)^2.


2

Expressions involving indeterminates are referred to as algebraic or symbolic


expressions (as opposed to arithmetical ).
When a variable is created, it has the status of an indeterminate (it is
`unassigned'). However, a variable can be assigned a value. The simplest
values are numerical constants
> c:=3;
c := 3
The above statement is called an assignment statement. The assignment
operator is `:=', and not the equal sign `=', which in Maple has a di er-
ent meaning. Forgetting the colon before the equal sign in an assignment
statement is a classic beginner's mistake, much like forgetting the semi-
colon at the end of an expression. Variables can also be assigned the value
2.3. SOME MAPLE 15
of arithmetical and algebraic expressions (and indeed of any valid Maple
expression)
> c:=10^10;
c := 10000000000
> c:=(a+b)^2;
c := (a + b)2
> %%,%;
10000000000; (a + b) 2

One sees that the value of an assignment statement, captured by the ditto
variables, is equal to the value of the expression being assigned, and not to
the assignment itself. This is because the assignment statement is not an
expression, and so it does not have a value.
Once a variable is assigned a value, the latter is substituted whenever
the variable's symbolic name appears in an expression
> a:=3:
> 2-a^a,c;
25; (3 + b)
2

To return the variable to the status of indeterminate, we must use the right
quotes as follows
> a:='a';
a := a
> 2-a^a,c;
2 aa; (a + b) 2

This can also be done temporarily within an expression


> z:=11^11;
z := 285311670611
> z+'z';
285311670611+ z
WARNING. A variable cannot be de ned in terms of itself (recursive de -
nition ). Thus, if the variable danger was not previously assigned a value,
the statement
> danger:=danger+1;
generates a warning message that a recursive de nition has just been made.
At the rst attempt of evaluation, such as
> danger;
Maple will try to determine the value of the right-hand side of the assign-
ment statement, which is the expression danger+1. To do so, Maple rst
16 CHAPTER 2. INTEGERS AND RATIONALS
needs to evaluate danger, but because the name danger evaluates to it-
self, Maple will be referred repeatedly to the same assignment, until the
computer's memory is full and Maple grinds to a halt!
If, on the other hand, a variable has been previously assigned a value,
expressions of this type are perfectly legitimate
> z:=3:
> z:=z+1;
z := 4
In this case, the name z in the expression z+1 evaluates to 3 rather than to
itself, so that the expression z+1 evaluates to 4, which is the value assigned
back to z.
Maple allows great freedom in choosing variables' names. A name will
normally start with a letter, possibly followed by letters, digits and un-
derscores, totalling up to over half a million characters! Long, descriptive
names are commonplace in modern programming style
> first square:=15140424455100^2;
first square := 229232452680590131916010000
> second square:=158070671986249^2;
second square := 24986337342184324378845090001
> 109*first square-second square;
1
Note the use of the underscore to join words. The same e ect can be
achieved by means of upper-case letters, e.g., FirstSquare. It must be re-
membered that Maple distinguishes between upper- and lower-case letters.
So the names Aa, aA, aa and AA are all di erent.
Maple has reserved words, which have a pre-de ned meaning, and which
should not be used for a di erent purpose. Some of them will not be
accepted as valid names (such as and, stop, from), while others are names
of Maple built-in functions which it would be unwise to overrule (such as
the names of the trigonometric functions sin, cos, tan, etc.).
Substitutions
Assigning a value to a variable by means of the assignment operator `:='
is not always desirable. If the assignment is temporary, it is often more
convenient to use the substitution function subs
> s:=x+y+x^2+y^2+x*y;
s := x + y + x2 + y 2 + xy
> subs(x=100,y=99,s);
29900
2.3. SOME MAPLE 17
> s;
s := x + y + x2 + y 2 + xy
Substitution requires the operator `=' rather than the assignment operator.
Note that x and y have been assigned a value with a single command, and
that after the substitution, the variable s still retains its value, so it can be
used again (even in the same expression)
> subs(x=1,s)-subs(y=z^2,s);

2 + 2y + y x z x xz z
2 2 2 2 4
(2.9)
Assigning values to x and y by means of the assignment operator would
cause the original value of s to be temporarily lost. Its recovery would
require clearing variables, and constructs of the type (2.9) could not be
performed.
> x:=100:y:=99:s;
29900
> x:='x':y:='y':s;
x + y + x2 + y 2 + xy
If more than one substitution is performed with a single subs command,
Maple will proceed left to right in the substitution list. This form of multiple
substitution is called sequential. In general, the order in which substitutions
are performed matters, e.g.,
> subs(a=b,b=c,a+b+c);
3c
> subs(b=c,a=b,a+b+c);
b + 2c
(Study the above example with care.) In order to carry out a simultaneous
substitution, it is necessary to group the substitution equations within curly
brackets
> subs(a=b,b=c,c=a,a^3+b^2+c);
a3 + a2 + a
> subs(fa=b,b=c,c=ag,a^3+b^2+c);
b3 + c2 + a
The e ect of the latter substitution is to permute the variables a, b, and c.
Example 2.3. Evaluate the following algebraic expression
  
1
4 a a b +b 1 9a :
1
2

b+1
2 4

(b 1) 2
18 CHAPTER 2. INTEGERS AND RATIONALS
for a = 2 and b = 1. We build this expression starting from the sub-
expression 1=a a, using ditto variables and substitutions. Then we sub-
2

stitute numerical values for a and b.


> 1/a^2-a:
> 4*%*subs(a=-b^2,%)-9*a/subs(a=b-1,%):
> subs(a=2,b=-1,%):
22
Relational expressions
We consider the problem of comparing the value of arithmetical expres-
sions, with respect to the ordering relation (2.4) de ned in Z. For instance,
suppose we want to decide which is the largest between 2 and 3 . A
1000 600

straightforward way to do this is to take the di erence between the two


numbers and see whether it is positive, negative, or zero.
> 2^1000-3^600;

1071508607186265447020721164266013135159412775893191176596n
8472890921952544339378013021020630393279855155792260144674n
6605212834809970127613668968844556474896643683504041891476n
0047746073703282588498083618354488963128411684797363293441n
7856017249719920313704260788202771289845415370457786694613n
325762937375
Because this number is positive, we conclude that 2 > 3 . However,
1000 600

the above procedure is clearly unsatisfactory, since it requires generating


all the digits of a very large number, when all we need is its sign.
Maple o ers the possibility of obtaining a straight answer to questions
such as `is 2 greater than 3 ?'.
1000 600

> evalb(2^1000 > 3^600);


true
The above expression features the relational expression 2^1000 > 3^600,
which is evaluated with the Maple function evalb.
A relational expression is one that links numerical and logical data. It
consists of two arithmetical expressions which are compared by means of
an equality or an inequality, called a relational operator. If the relation
is satis ed, the expression evaluates to the Boolean (or logical ) constant
true and to the constant false otherwise (unless Maple has diÆculties in
deciding, in which case it returns the value F AIL). The Maple relational
operators are:
= equal >= greater or equal > greater
<= less or equal < less <> not equal
2.3. SOME MAPLE 19
To evaluate a relational expression to a Boolean value, we use the function
evalb (evaluate to Boolean). Explicit evaluation is needed here because
such expressions may also occur as equations or inequalities, which can be
manipulated algebraically
> evalb(-3<-2), evalb(-3=-2);
true; false
> 1+1=z;x<-3*y^2;
2=z
x< 3y 2

> %%+%;
2+x < z 3y 2

We apply the above construct to the problem of comparing distances in


Z with Maple. To measure a distance, we make use of the absolute value
function (2.5), which is implemented in Maple by the function abs
> abs(-12),abs(53*9100^2-66249^2);
12; 1
The combined use of evalb and abs is illustrated in the following example.
Example 2.4. Let n = 100 . Which of n = 101 or n = 99 is
100
1
99
2
101

closer to n? To nd out, we establish the truth or falsehood of the inequality


jn n1 j < jn n2 j :

> n:=100^100:n1:=101^99:n2:=99^101:
> evalb(abs(n-n1) < abs(n-n2));
true
So n is the closer of the two to n.
1

Exercises
Exercise 2.3. By means of some experiments, verify the rules concerning
the order of evaluation of arithmetical operators.
Exercise 2.4. In this exercise you should use the function subs.
(a) Construct the following algebraic expression
1+z+z +z +z ;
2 3 4

whence evaluate the sum


1+2+2 +2 +2 1 3 3 3 3 +1 4 +4 4 +4 :
2 3 4 2 3 4 2 4 6 8
20 CHAPTER 2. INTEGERS AND RATIONALS
(b) Construct the following algebraic expression
1+x+x +x ; 2 3

1 y y y 2 3

whence evaluate the arithmetical expression


1+3+3 +3  1+2 2 +2 :
2 3 2 3

1 2 2 2 1 3+3 3
2 3 2 3

Exercise 2.5. In this exercise you should not display any digit. Display
only the minimal output required to establish your result.
(a) Place the following integers in ascending order
100 ; 80 ; 60 ; 40 ; 20 :
100 120 140 160 180

(b) Find the largest integer whose 17th power is smaller than 10 . 30

2.4 Divisibility

Divisibility is one of the most important concepts in arithmetic. We begin


with some de nitions.
Given two integers d and n, we say that d divides n (or d is a divisor of
n, or n is a multiple of d) if there exists an integer q such that n = dq . Such
q is called the quotient of the division of n by d. With reference to (2.3)
and following comments, we see that divisibility characterizes the extent to
which the missing equation x  a = b can be solved.
If d divides n we write d j n, and if d does not divide n we write d 6 j n.
Thus, 3 j 21 because 21 = 3  7, while 12 6 j 21 because the equation 21 = 12  q
has no integer solution q. An integer is even if it is divisible by 2, and odd
if it is not. Two integers have the same parity if they are both even or both
odd. If one is even and the other is odd, they have opposite parity.
Since for all n we have n = 1  n, it follows that 1 and n divide n, and
since 0 = d  0, we see that any integer divides 0. Also if d divides n, so
does d. For this reason, in issues involving divisibility it is customary
to consider the positive divisors only. A proper divisor d of n is a divisor
which is neither equal to 1 nor to n.
Example 2.5. The number 0 has in nitely many divisors, 12 has six
divisors (1,2,3,4,6, and 12), four of which are proper, 11 has two divisors (1
and 11), and 1 has one divisor.
Divisibility has a simple geometrical interpretation. If d divides n, we
can arrange n points on the plane to form a rectangular array with d rows.
Interchanging rows and columns, that is, rotating the array by a right an-
gle, yields another array with q = n=d rows. This geometrical argument
shows that divisors come in pairs, that is, if d divides n then also n=d
2.4. DIVISIBILITY 21
4 3
z }| {
z }| {
8
<    
8
>   
(i) 3 :     (ii) 4 >
<
  
    :   
  
Figure 2.4: Graphical representation of the divisibility of n = 12 by (i )
d = 3, and (ii ) by its twin divisor n=d = 12=3 = 4.

divides n and vice versa. The above symmetry has an arithmetical coun-
terpart: if d divides n, the role of d and q = n=d in the equation n = d q is
interchangeable.
Because every divisor d of n has the twin divisor n=d, can we conclude
that the number of divisors of an integer is always even? Not necessarily,
because d and n=d may coincide, giving n = d , a square. Thus, an integer
2

is a square precisely when it has an odd number of divisors.


z
4 {
}|
8
>    
<
4>    
:    
   
Figure 2.5: The integer n = 16 = 4 is a square, and the divisor d = 4
2

coincides with its twin n=d = 16=4 = 4.


This pairing of divisors has an important consequence.p Suppose that
d is a divisor of n such that d  n (that is, d  n). Then we have
2

n=d  1, whence (n=d) = n(n=d )  n. This shows that


2 2 2
p the twin divisor
n=d of d satis es the inequality (n=d)  n (or n=d  n). So in order to
2

nd all divisors of n, we must test for divisibility only those integers d for
which 1  d  n (that is, 1  d  pn).
2

Example 2.6. To nd the divisors of 30, we must test for divisibility


all integers up to and including 5. The divisors of 30, regrouped in pairs,
are (1; 30), (2; 15), and (3; 10). The divisors of 36 = 6 are (1; 36), (2; 18),
2

(3; 12), (4; 9), and 6. Because 36 is a square, one of its divisors has no twin,
and the number of divisors of 36 is odd.
Quotient and remainder
Given two natural numbers d and n, with d 6= 0, one can always nd two
uniquely determined natural numbers q and r such that
n = dq + r 0  r < d: (2.10)
22 CHAPTER 2. INTEGERS AND RATIONALS
The integers q and r are called the quotient and the remainder of the division
of n by d, respectively. The existence of such integers with the stated
properties can be established as follows. We arrange n points on the plane
to form a pattern which is as close as possible to a rectangular array with d
rows. In other words, we maximize the number of columns with d elements,
as illustrated below for the case n = 14 and d = 3.
q=4
z }| {
8
<     
d=3      r=2
:
    
Figure 2.6: Dividing 14 by 3 gives quotient 4 and remainder 2.
Let q be the number of complete columns (d elements). Then there exists,
at most, one incomplete column, whose number r of elements is necessarily
smaller than d (otherwise, we could form more complete columns). This
establishes the equation and the inequality in (2.10). The condition that
r be smaller than d is what makes the de nition of remainder interesting.
In particular, it follows that d divides n precisely when the corresponding
remainder is zero, in which case the n = dq points form a rectangular array
with d rows.
Note that one speaks of the quotient of the division of n by d whether or
not d divides n. When d divides n, the de nition (2.10) with r = 0 reduces
to that given at the beginning of this section.
The greatest common divisor
A common divisor of two integers is an integer that divides both. Thus, if
n = dq and n0 = dq 0 , then d is a common divisor of n and n0 .
8 8
<    <       
(i) 3 :     (ii) 3 :       
          
Figure 2.7: The integers (i ) 12 = 3  4 and (ii ) 21 = 3  7 have the common
divisor 3.
If d divides n and n0, then d also divides n  n0. Indeed, from n = dq
and n0 = d0 q, we have n  n0 = d (q  q0 ). (This is also clear from the above
gure.)
The greatest common divisor of two integers x and y, denoted by gcd(x; y),
is the largest among the common divisors of x and y.
gcd( 15; 21) = 3 gcd(1; 7) = 1 gcd(0; 7) = 7:
2.4. DIVISIBILITY 23
By de nition, gcd(x; y) = gcd(jxj; jyj). Also, gcd(x; 0) = jxj, and, for
convenience, gcd(0; 0) is de ned to be zero. Thus, gcd(x; y)  0. The
de nition of greatest common divisor may be extended to the case of more
than two integers in an obvious fashion. Thus, gcd(x ; : : : ; xn ) is the largest
1
among the common divisors of the n integers x ; : : : ; xn .
1
The integers x ; : : : ; xn are said to be relatively prime, or coprime, if
1
their greatest common divisor is equal to 1. For example, 14; 15 are rel-
atively prime, and so are 10; 15; 18. The latter example shows an inter-
esting phenomenon. We have gcd(10; 15; 18) = 1, in spite of the fact that
gcd(10; 15) > 1, gcd(10; 18) > 1 and gcd(15; 18) > 1. So when n is greater
than 2, n integers may be relatively prime without being so when consid-
ered in pairs. We say that n integers are pairwise relatively prime if any two
of them are. For instance, 26; 33; 35 are pairwise relatively prime. Pairwise
relative primality is stronger than relative primality, in the sense that the
former implies the latter (see exercises).
The least common multiple of two nonzero integers x and y, denoted
by lcm(x; y), is the smallest positive integer divisible by x and y. For any
integer x we de ne lcm(x; 0) = 0. For instance, lcm(12; 21) = 84. As for
the greatest common divisor, the de nition of least common multiple can
be extended to the case of more than two integers.
Maple functions for divisibility
Maple implements a large number of arithmetical functions, including all
elementary functions related to divisibility.
The functions iquo(n,d) and irem(n,d) return the quotient and the
remainder, respectively, upon dividing n by d. (The pre x i means `integer'.
Maple also has the functions quo, rem which carry out the corresponding
operations for polynomials, as we shall see.) These functions accept also
negative arguments, in which case the de nition of quotient and remainder
given in (2.10) is generalized as follows
n = dq + r 0  jrj < jdj; n r  0: (2.11)
The behaviour of iquo and irem when one or both arguments are negative
is best illustrated with examples.
> iquo(23,7),iquo(23,-7),iquo(-23,7),iquo(-23,-7);
3; 3; 3; 3
> irem(23,7),irem(23,-7),irem(-23,7),irem(-23,-7);
2; 2; 2; 2
We see that the remainder is negative whenever n is negative, while the
quotient is negative if n and d have opposite signs.
The function igcd(x1,...,xn) and ilcm(x1,...,xn) return the great-
est common divisor and the least common multiple, respectively, of the
24 CHAPTER 2. INTEGERS AND RATIONALS
integers x1 through xn. For a summary of the main Maple arithmetical
functions, see the last section of this chapter.
Example 2.7. Divisibility and greatest common divisor. There is a close
relationship between divisibility of b by a and the greatest common divisor
of a and b. Indeed, if a > 0, then a divides b precisely when gcd(a; b) = a.
To see this, observe that if gcd(a; b) = a, then ajb, by de nition of greatest
common divisor. Conversely, let ajb. Because aja, then a divides both a and
b, and since a is the largest integer dividing a, it follows that gcd(a; b) = a.
Example 2.8. Divisibility and remainder. We can use irem to test di-
visibility, since d divides n exactly when irem(n,d) is equal to zero, in
which case evalb(irem(n,d)=0) evaluates to true. For instance, 2 1 191

is divisible by 383
> evalb(irem(2^191-1,383)=0);

true (2.12)
Pythagorean triples 
A Pythagorean triple is a set of three positive integers (x; y; z) such that
x +y =z :
2 2 2
(2.13)
For instance, (3; 4; 5) is such a triple. The elements of a triple are the
lengths of the sides of a right triangle, from Pythagoras' theorem, and so the
problem of nding Pythagorean triples amounts to nding right triangles
whose sides all have integer length.
If (x; y; z) is a triple, then by multiplying equation (2.13) by d we 2

nd that (dx; dy; dz) is another triple. So from any triple (x; y; z) one can
generate in nitely many of them, by letting d = 1; 2; 3; : : : . If d > 1 then
the elements of such a triple are not relatively prime, having the common
divisor d.
Conversely, if d is the greatest common divisor of x; y, and z, then d 2

can be cancelled out from equation (2.13) and one nds that (x=d; y=d; z=d)
is also a triple whose elements are relatively prime. A Pythagorean triple
with this property is said to be primitive.
It turns out that all triples can be derived from primitive ones, so the
primitive case is the most interesting one. The following algorithm for
nding all primitive Pythagorean triples is due to Diophantus of Alexandria
(about 250 a.d.).
Consider two positive integers p and q such that (i) p > q, (ii) p and
q are relatively prime, (iii) p and q are of opposite parity (i.e., one is
even and the other is odd). Then (2 p q; p q ; p + q ) is a primitive
2 2 2 2

Pythagorean triple. That this is actually a triple follows from the algebraic
identity
(2 p q) + (p q ) = (p + q )
2 2 2 2 2 2 2
(2.14)
2.5. RATIONALS 25
which is valid for all p and q. It is possible to prove that such a triple is
primitive, and that all primitive triples can be obtained in this way (see
exercises that follow).
The primitive triples for p  7 are tabulated below
PYTHAGOREAN TRIPLES
p q x y z

2 1 4 3 5
3 2 12 5 13
4 1 8 15 17
4 3 24 7 25
5 2 20 21 29
5 4 40 9 41
6 1 12 35 37
6 5 60 11 61
7 2 28 45 53
7 4 56 33 65
7 6 84 13 85
Exercises
Exercise 2.6. Show that every common divisor of two integers divides
their greatest common divisor.
Exercise 2.7. Show that if n integers are pairwise relatively prime, they
are relatively prime.
Exercise 2.8. Find all primitive Pythagorean triples corresponding to
p = 987 and q  970 ( ve in all).
Exercise 2.9. Find a primitive Pythagorean triple whose elements all
have at least 20 decimal digits (i.e., x; y; z  10 ). Verify directly that
19

your solution is indeed a primitive triple, that is, that x, y, and z satisfy
equation (2.13) and are relatively prime.
Exercise 2.10 .
 Prove that if p > q > 0, gcd(p; q) = 1, and p and q have
opposite parity, then x = 2pq; y = p q , and z = p + q are pairwise
2 2 2 2

relatively prime. This, along with (2.14), establishes that (x; y; z) is a prim-
itive Pythagorean triple. (In this exercise, you will need the fundamental
theorem of arithmetic | see below.)
Exercise 2.11
 Prove that any primitive triple can be obtained with
.
Diophantus' algorithm.
2.5 Rationals

The operations of sum, subtraction, and multiplication can be performed


unrestrictedly in Z. And division? We have seen that if a and b are integers,
26 CHAPTER 2. INTEGERS AND RATIONALS
then a=b is not necessarily an integer, and indeed the notion of divisibility is
introduced precisely to handle this possibility. We say that Z is not closed
under division.
To characterize the lack of closure solely in terms of the elements of Z
and the operation of multiplication, we note that if a and b are integers,
with a 6= 0, then the equation
xa = b a; b 2 Z; a 6= 0 (2.15)
cannot always be solved for x 2 Z. Note the structural similarity between
equations (2.1) and (2.15), with N and + in the former playing the same
role as Z and  in the latter.
To solve this problem, we adjoin to Z the solutions of the equations
(2.15), which are called rational numbers. They form a set denoted by Q .
A rational number is the ratio of two integers (whence its name!)
x = ab a; b 2 Z; a 6= 0: (2.16)
If a divides b, then b = aq, and the number x in (2.16) is equal to q, an
integer. By letting a = 1 in (2.15) and letting b run over Z, we obtain all
elements of Z. This means that all integers are rational, and the inclusion
relation (2.2) extends to
N  Z  Q:
Clearly not every rational is an integer.
The arithmetical operations with rationals are de ned from those in Z
as follows
a c adbc a c ac a c a d
b d
 = bd  =
b d bd
 = 
b d b c
where we have assumed that b  d 6= 0, and also that c 6= 0 in the last
equation. Now sum, subtraction, multiplication, and division of elements
of Q yield an element of Q , with the only exception of division by zero. We
have at last constructed a set where all four arithmetical operations can be
performed unrestrictedly. A set with these properties is very special: it is
called a eld (see section 12.3).
The set of positive rational numbers is denoted by Q . Thus, Q is the
+ +

set of numbers x of the form (compare with (2.16))


x= ab a; b 2 N : +

The very de nition of a rational number creates a problem of represen-


tation. Let a = 6 and b = 4. In nitely many pairs of integers exist, which
represent the same rational b=a
x=
2 2 4 4 6 6
3 = 3 = 6 = 6 = 9 = 9 = :
2.5. RATIONALS 27
To obtain a unique representation we shall require that a be positive, and
that a and b be relatively prime. A rational b=a satisfying these require-
ments is said to be in reduced form. Thus, the reduced form of 4=( 6) is
2=3. The reduced form a ords the most economical representation of a
rational number.
Maple always represents and displays rationals in reduced form
> 4/(-6);
2
3
Maple provides the function numer and denom which return the numerator
and the denominator of the value of a rational expression, respectively
> 22/8:%,numer(%),denom(%);
11 ; 11; 4
4
Rationals constitute a new type of object in Maple | a new data type.
To nd out what Maple calls them, we use the function whattype
> whattype(2),whattype(2/3);
integer; fraction
Example 2.9. The fact that Maple always represents rationals in reduced
form yields a straightforward method to test divisibility, which consists of
evaluating the expression a=b, and then checking whether or not the result
is an integer
> 111111111111/1111:%,whattype(%);
100010001; integer
> 111111111111/11111:%,whattype(%);
111111111111; fraction
11111
Thus, 1111 divides 111111111111 whereas 11111 does not.
Ordering and distance in Q
The set Q inherits from Z ordering and distance, as de ned in section 1.1.
This means that we can decide about the ordering of any two rationals from
an order relation involving only integers
a c
 () ad  bc bd > 0;
b d
where the symbol `()' means that the two relations on the opposite sides
are equivalent | they are either both true or both false (see Chapter 3).
Similarly, we de ne the absolute value jxj of a rational x, in terms of a
ratio of absolute values of integers
a
b
= jjabjj :
28 CHAPTER 2. INTEGERS AND RATIONALS
As we did for the integers, we then let the distance between x and y be
jx yj.
Let x = b=a be a rational number. Then from (2.10) integers q and r
can be found such that
b = qa + r 0  r < a:
Dividing out this equation by a, we obtain
b
x=
a
= q + ar : (2.17)
The integer q | the quotient of the division of b by a | is the integer part
of x. The rational number r=a is called the fractional part of x, denoted
by fxg. Thus
23 = 3 + 2 =)  23  = 2 23 = 4 + 5 =)  23  = 5 :
7 7 7 7 7 7 7 7
Note the asymmetry between positive and negative values of x. In partic-
ular, with reference to equation (2.17), we see that q is the largest integer
not greater than x if x is positive, and the smallest integer not smaller than
x if x is negative.
Example 2.10. Let x be a non-negative rational number. From (2.17)
we see that the fractional part of x is given by irem(numer(x),denom(x))/
denom(x). (The Maple function frac(x) does the same.) For negative
values of x both expressions give the fractional part in accordance with the
more symmetrical equation (2.11) in place of (2.10)
> -23/7:frac(%);
2
7
Example 2.11. Let r = 21=34; r = 55=89; r = 34=55. Show that r
1 2 3 2
lies between r and r . We use the triangle inequality (2.6)
1 3
> r1:=21/34:r2:=55/89:r3:=34/55:
> evalb(abs(r1-r3)=abs(r1-r2)+abs(r2-r3));
true
The minimal distance between two distinct integers is 1, and in particu-
lar, 1 is the smallest positive integer. We now show that, by contrast, there
is no minimal distance between rationals, whence there is no smallest posi-
tive rational. This important property is a consequence of the Archimedean
property of the rationals, stating that for all positive rationals x and y there
exists a positive integer n such that nx > y. In words, a suÆciently large
number of copies of any positive quantity can be made arbitrarily large.
Now let y = 1 and let x be a nonzero rational. Then jxj > 0, and the
2.5. RATIONALS 29
Archimedean property ensures that we can nd a positive integer n such
that n jxj > 1 or
1 < jxj:
n
No matter how small x is, we have found a positive rational 1=n which is
closer to zero than x. So there is no smallest positive rational.
In the above construction, the closer x is to zero, the larger n will be.
This observation can be generalized: if two rationals are close to each other,
then the product of their denominators must be large (and therefore at least
one of them must have a large denominator). To prove this, let us assume
that the distance between x = a=b and y = c=d is small (in particular, less
than 1). Then there exists a positive integer n such that
jx yj = ad cb = jad cbj  1 :
bd jbdj n
(2.18)
Because x 6= y, it follows that ad cb 6= 0, and since all quantities are
integers we have that jad cbj  1. From this and the inequality in (2.18)
we obtain
jbdj  jad cbj n  n: (2.19)
This inequality shows that the product bd of the denominators of x and y
is at least as large as n, in absolute value. From (2.18) we see that as x
approaches y, we can let n approach in nity, and with it the product of the
denominators, from (2.19).
A straightforward method for nding a rational close to a given rational
is based on the following construction. For n > 0 we consider the set n Z of
1

all rationals with denominator n. These are the numbers of the form k=n,
for k 2 Z. The set n Z consists of equally spaced rationals with spacing
1

1=n. Note that


1
Z Z Q n  1:
n
For any choice of k, the element k=n 2 n Z is separated from its two neigh-
1

bouring elements (k  1)=n by the minimal distance 1=n.


Let now x = a=b be the given rational. Then, for every m > 0 we have
x = am=bm, whence
a
2 1Z
b bm
m = 1; 2; : : : :

The neighbours of x in bm Z, given by


1

am  1
bm
lie at distance 1=bm from x. So, by choosing m to be suÆciently large, we
can make this distance be as small as we please.
30 CHAPTER 2. INTEGERS AND RATIONALS
While nding a rational close to a given rational is straightforward, the
problem becomes much more subtle if we try at the same time to minimize
the size of the denominator. For given n, the minimal denominators will
occur when ad bc = 1 and when b and d are of similar magnitude, each
approximately equal to the square root of n.
Example 2.12. Find a rational lying at distance smaller than 10 from
4

x = 96=145. We let a = 96, b = 145, and n = 10 , and compute the


4

smallest m for which mb > n.


> a:=96:b:=145:n:=10^4:
> m:=iquo(n,b)+1;
m := 69
A desired rational is then the right neighbour of x in bm Z, given by
1

> (a*m+1)/(b*m);
1325
10005
But we can do better with a much smaller denominator, e.g.,
> c:=47:d:=71:
> abs(a/b-c/d);
1
10295
With reference to (2.19) note that
> abs(a*d-b*c);
1
(The rational 47/71 was found with a number-theoretical technique called
continued fractions. See (2.22) for an example.)
Example 2.13. Let a=b and c=d be two rational numbers, in reduced
form. Their mediant is de ned as
a+c
b+d
: (2.20)
We show that the mediant of two reduced rationals lies between them. Let
us assume that a=b < c=d. Then, since bd and d(b + d) are positive, we have
a c
<
b d
() ad < bc () ad + cd < bc + cd
() (a + c)d < (b + d)c () ab ++ dc < dc :
The other inequality is proven similarly. Another prominent rational lying
between a=b and c=d is their midpoint
1  a + c  = ad + bc : (2.21)
2 b d 2bd
2.5. RATIONALS 31
The denominator of the midpoint is, in general, much larger than that of
the mediant. For this reason, the mediant may be used as a simple device
for identifying low-denominator rationals between two given rationals.
Exercises
Exercise 2.12. Evaluate the following rational expression, rst by hand,
then with Maple  
1 + 13  1 + 181 122 41
4   5 2  3  + 10
9 14 3 56 28
Exercise 2.13. Consider the following expression, called a continued frac-
tion
a+
1 (2.22)
b+
1
a+
1
b+
1
a
(a) Construct it by means of a single Maple expression.
(b) By repeated use of the ditto variable %, construct it recursively, in four
or ve steps. [Hint: begin from the end.]
(c) Use the function subs to evaluate (2.22) for a = b = 1, and then for
a = 10 and b = 20.
Exercise 2.14. Let a = 5001999958 and let b = 5004400966.
(a) Compute the greatest common divisor d of a and b.
(b) Verify the following equation and inequalities
a = bq + r 0r<b
where q is the quotient and r is the remainder upon dividing a by b.
(c) Verify that Maple represents a=b in reduced form, that is, check that
a=b is displayed as a0 =b0 where
a b
a0 = b0 =
d d
and d is as above. The integers a and b are extracted from the value of
0 0
a/b by means of the Maple functions numer and denom, respectively.
(d) Find a proper divisor of a that does not divide b.
Exercise 2.15. Let a = 10 20 and let b = 2 1. Determine the
20 10 60

integer which is closest to a=b.


Exercise 2.16. Let
x=
89 377 987
144 y = 610 z = 1597 :
32 CHAPTER 2. INTEGERS AND RATIONALS
(a) Consider the triangle inequalities
(i) jx zj  jx yj + jy zj (ii) jx yj  jx zj + jz yj:
Verify that strict inequality holds in case (i), and equality holds in case
(ii).
(b) Find a rational number r lying between x and z, which is closer to z
than y is. The denominator of r should be as small as possible (there is a
solution with a 3-digit denominator; can you nd it?).
2.6 Primes

A positive integer n greater than 1 is said to be prime if it has precisely two


divisors: 1 and n (or, equivalently, if it has no proper divisor). If this is not
the case, we say that n is composite. Note that 1 is not considered prime,
for convenience (see below). There are 25 primes less than 100. They are:
2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; (2.23)
53; 59; 61; 67; 71; 73; 79; 83; 89; 97:
Euclid, around 300 b.c., proved that there are in nitely many primes. The
number of primes not exceeding x is denoted by (x). Thus, (1) = 0,
 (11) = 5,  (100) = 25. Here is a brief table of this very important
function
x  (x)

10 4
10 2
25
10 3
168
10 4
1; 229
10 5
9; 592
10 6
78; 489
10 7
664; 579
10 8
5; 761; 455
10 9
50; 847; 534
10 10
455; 052; 511 (2.24)
The density of primes decreases slowly. While a quarter of the integers
less than 100 are prime, the proportion of primes among the rst 10 billion
integers has dropped to less than 5%.
The arithmetic in Z is based on the following result.
Theorem 1 (the fundamental theorem of arithmetic). Every integer greater
than one can be expressed as a product of primes, and this factorization is
unique up to the order of the factors.
2.6. PRIMES 33
Thus, 12 = 2  3. You can see why 1 is not considered prime. If it
2

were, then 12 = 1  2  3 would be a di erent decomposition into primes.


2

In general, the prime decomposition of an integer n, positive or negative,


takes the form (n 6= 0; 1)
k
Y
n = pe1  pe2    pek = 
1 2
k
pei i ; (2.25)
i=1

where we stipulate that the primes pi are all distinct and that the exponents
ei are positive integers. The primes p ; : : : ; pk are called the prime divisors
1
of n.
If n has the prime decomposition (2.25), and n = dq, then the prime
decomposition of dq is the same as that of n, from the fundamental theorem.
So if d divides n, the prime divisors of d must also be prime divisors of n,
and their exponent cannot exceed the corresponding exponent for n.
When constructing a divisor of n from (2.25), we nd that there are
ei + 1 possible choices for each exponent ei (from 0 to ei ). So the number
 (n) of divisors of n is given by
 (n) = (e + 1) (e + 1)    (ek + 1):
1 2 (2.26)
Example 2.14. We have
84 = 2  3  7 : 2 1 1

Thus, 84 has three prime divisors. In the notation of equation (2.25) we


have k = 3, p = 2, p = 3, p = 7, e = 2, e = 1, e = 1. The number of
1 2 3 1 2 3
divisors of 84 is (84) = (e + 1)(e + 1)(e + 1) = 3  2  2 = 12.
1 2 3

Example 2.15. We determine the structure of the prime decomposition


of all integers with 10 divisors. From (2.26) we have
(e + 1) (e + 1)    (ek + 1) = 10 = 2  5:
1 2

We have two possibilities, namely k = 1; e = 9, or k = 2; e = 1; e = 4.


1 1 2
Thus, if n has 10 divisors, its prime decomposition must have the form
n=p or n = p p
9
1 1
4
2

where p and p are arbitrary distinct primes. From the in nitude of primes,
1 2
it follows that the number of integers with 10 divisors is in nite.
Maple has a function called ifactor which returns the unique prime
decomposition of an integer, as referred to in the fundamental theorem of
arithmetic
> ifactor(3^52-2^52);
(5) (13) (53) (79) (1093) (13761229) (29927) (4057)
2
34 CHAPTER 2. INTEGERS AND RATIONALS
Note that Maple is rather untidy | the prime factors are not necessarily
displayed in ascending order.
The existence of the fundamental theorem gives us a systematic way
of constructing all divisors of any given integer n, once we have its prime
decomposition. Obtaining the prime decomposition of an integer is concep-
tuallyp easy. All that is needed is testing the divisibility of n by all primes
p  n. However, if n is large, this procedure is hopelessly slow. But even
with the most sophisticated factorization algorithms (such as the one im-
plemented by the function ifactor), factoring a large integer into primes
remains an extremely diÆcult computational problem.
Example 2.16. The function ifactor a ords a test for primality, al-
beit a rudimentary one. For instance, let us decide whether or not p =
31418506212244678577 is prime
> ifactor(31418506212244678577);
(7949) (7927) (7933) (7919) (7937)
> expand(%);
31418506212244678577
So p is not prime. The multipurpose function expand is doing just that, ex-
panding the product, thereby allowing us to recover the original entry. This
method of testing primes is ineÆcient, and it turns out that it is possible
to decide whether or not an integer is prime without actually computing
its prime decomposition.
Example 2.17. The function isprime(x) returns the value true if x is
prime and the value false otherwise
> isprime(31418506212244678577);
false
> isprime(7949);
true
Strictly speaking, the above description of isprime is incorrect. This func-
tion runs a probabilistic primality test, meaning that when it returns the
value true, the argument is `very likely' to be a prime. In practice, not a
single counterexample for which such test has failed is known, and if such
counterexample exists, it has been conjectured to be hundreds of digits
long. So you may trust isprime after all!
Example 2.18. A trapdoor function. If you run the commands ifactor
and expand of the previous exercise, you will not fail to notice that factor-
ization is a lot more time-consuming than multiplication. Multiplication is
a trapdoor function, easy to do but very diÆcult to undo. This very inter-
esting phenomenon is of great theoretical interest, and has applications in
cryptography. To get a feeling for the behaviour of this trapdoor function,
2.6. PRIMES 35
identify some large primes, multiply them together, and then attempt to
undo the multiplication by means of ifactor. Monitor the computation
time with the function time (see online documentation).
The Mersenne numbers 
The number 2 1279
1 computed in (2.7) is very interesting: it is prime, and
so is 1279, the exponent of 2. Its primality was discovered in 1952 using a
computer, and at that time it was the largest known prime. The numbers
of the form
Mp = 2p 1 p prime
are called Mersenne numbers, from the name of the 17th-century priest,
Father Marin Mersenne, who rst studied their properties. He originally
thought that they were all primes, but this turned out not to be the case.
For instance, we have already veri ed that M is not prime (see (2.12)),
191
and indeed (as of December 2000) Mp has been shown to be prime only for
the following values of p
2; 3; 5; 7; 13; 17; 19; 31; 61; 89; 107; 127; 521; 607; 1279; 2203; 2281;
3217; 4253; 4423; 9689; 9941; 11213; 19937; 21701; 23209; 44497;
86243; 110503; 132049; 216091; 756839; 859433; 1257787; 1398269;
2976221; 3021377; 6972593
(2.27)
It is not known whether there are in nitely many Mersenne primes. The
importance of Mersenne numbers derives from the discovery, made by Lucas
in 1878, of a very eÆcient algorithm for testing their primality. It was
Lucas himself who found in this way the largest prime to be known before
the computer age, namely
> 2^127-1;
170141183460469231731687303715884105727
The current world record corresponds to the largest prime in (2.27), that
is, 2
6972593
1 with 2098960 digits.
By the time you read this page, this record may already have been bro-
ken: check the latest on Mersenne primes and other prime number records
on the web sites
http://www.mersenne.org
http://www.utm.edu/research/primes/
The primality of small Mersenne numbers can be tested with the func-
tion isprime. Thus, with reference to (2.23) and (2.27)
> isprime(2^89-1);
true
> isprime(2^97-1);
false
36 CHAPTER 2. INTEGERS AND RATIONALS
Even though the algorithm used by isprime is quite sophisticated, this
function does not implement Lucas' test, which works only for Mersenne
primes. Maple has specialized software for Mersenne numbers | type
?mersenne for details.
An advanced account of prime number records can be found in [4]. For
the necessary background in arithmetic, see [5] or [2].
Exercises
Exercise 2.17.

(a) Determine the number of divisors of 20!


(b) Find all divisors of 472890989.
(c) Verify that 101 1 has 5 prime divisors, without displaying them.
4

Exercise 2.18.

(a) By means of the function prevprime, determine the largest prime


which is smaller than 10 . (Obtain information about prevprime through
8

the online help system.)


(b) Verify the result of part (a) directly, by testing for primality the integers
less than 10 , starting from 10 1 and working your way backward. You
8 8

must use the isprime function, but you should avoid testing those numbers
that are divisible by 2, 3, or 5 (for these you do not need Maple!).
Exercise 2.19. There are 25 primes less than or equal to 100. Indeed,
the 25th prime is 97, and the 26th prime is 101 | cf. (2.23).
(a) Verify the above statement with the function ithprime.
(b) Let (x) be the number of primes not greater than x (cf. 2.24). Use the
function ithprime to determine (x) for x = 1000; 2000; 3000; 4000; 5000.
(The function nextprime may also be useful.) This calculation is likely to
require a certain amount of trial and error, but you must show only the
minimal output that suÆces to prove your result.
(c) Let (x; n) = (x) (x n) be the number of primes that lie between
x n and x (x n excluded). Tabulate the values of  (x) and of (x; 1000).
Exercise 2.20. Find out which is the largest Mersenne prime you can
test for primality using isprime.
Exercise 2.21. Using the fundamental theorem of arithmetic, show that
for any x; y; z 2 Z, we have
gcd(x; y; z) = gcd(gcd(x; y); z) = gcd(gcd(x; z); y) = gcd(gcd(y; z); x):
This result says that the gcd of three integers can be computed by rst
computing the gcd of any two of them, and then the gcd of the latter and
the third integer.
Exercise 2.22. Show that for any m; n 2 Z, not both zero, the following
holds
gcd(m; n)  lcm(m; n) = m n: (2.28)
2.7. STANDARD LIBRARY FUNCTIONS 37
Exercise 2.23 .
 Find an integer greater than 10 which has exactly 21
40

divisors. Such integer should be as small as possible: explain your strategy.

2.7 Standard library functions

In this chapter, we have encountered several functions supported by Maple.


They are arithmetical functions such as iquo, igcd, and utility functions
such as subs. In the table below, we list some common arithmetical func-
tions. They belong to the so-called standard library, which is accessible
automatically by a user at any time during a Maple session. These func-
tions may be incorporated freely in any Maple expression.
ARITHMETICAL FUNCTIONS
function symbolic name example value
General:
absolute value abs(x) abs(-41) 41
factorial n! 9! 362880
binomial coe . binomial(x,y) binomial(6,3) 20
integer sq. root isqrt(x) isqrt(19) 4
maximum max(x,y,...) max(-22,0) 0
minimum min(x,y,...) min(-2,0,-3) 3
No. of digits length(x) length(1000!) 2568
Divisibility:
integer quotient iquo(x,y) iquo(-11,5) 2
integer remainder irem(x,y) irem(-11,5) 1
integer gcd igcd(x,y,...) igcd(21,6,-33) 3
integer lcm ilcm(x,y,...) ilcm(21,12) 84
Primes:
prime factoriz. ifactor(x) ifactor(24) (2) (3)
3

primality test isprime(x) isprime(7) true


ith prime ithprime(x) ithprime(10) 29
next prime nextprime(x) nextprime(8) 11
previous prime prevprime(x) prevprime(11) 7
Rationals:
numerator numer(x) numer(24/21) 8
denominator denom(x) denom(7) 1
fractional part frac(x) frac(-17/3) 2=3
Note that some Maple functions accept a single argument (e.g., abs,
38 CHAPTER 2. INTEGERS AND RATIONALS
ifactor), and some accept two arguments (e.g., binomial, iquo). For
other functions, the number of arguments is unspeci ed (e.g., igcd, max).
Example 2.19. Because the evaluation of quotient and of remainder are
closely related, one can compute both with a single call to either iquo or
irem. The function call iquo(a,b,'r') does not only compute the quo-
tient of the division of a by b, but it also assigns the value of the remainder
to the variable r. An analogous construction is possible for irem.
> iquo(27,7,'r'),r;
3; 6
> irem(27,7,'q'),q;
6; 3
Enclosing the third argument within right quotes is an essential precaution,
because both functions require it to be an unassigned variable's name. (For
an application, see section 5.1.)
Example 2.20. When the argument is an integer, the multipurpose func-
tion length returns the number of its decimal digits, with the convention
that the integer 0 has zero digits. If the argument is a symbol or a string,
length will return the number of characters. This function accepts any
data type as argument | see end of section 6.1.
Chapter 3

Sets and functions


In the previous chapter, we have come across a few important examples of
sets, such as the set N of natural integers, the set Z of integers, and the set
Q of rationals. In this chapter, we consider sets in greater generality. Then
we de ne functions, which establish relations between sets.

3.1 Sets
A set is a collection (family, aggregate) of objects. We shall regard it as
a primitive concept, without attempting to characterize it formally. The
simplest way of de ning a set is to list all its elements (whenever this is
possible!), by enclosing them within curly brackets, separated by commas.
For instance,
A = f 1; 3; 5g
is the set constituted by the three integers 1, 3, and 5. The order with
which the elements of a set are listed is irrelevant, and therefore two sets
are the same if they contain the same elements
A = f 1; 5; 3g = f5; 1; 3g = f5; 3; 1g; etc:

If x belongs to A, we write x 2 A, and x 62 A otherwise. Thus, if A =


fa; abg, then a 2 A and b 62 A.
We shall agree that any repeated element is to be counted only once
A = f7; 7; 0; 3; 7g = f7; 0; 3g:

This is a commonly adopted convention: sets with repeated elements are


often referred to as multisets.
It should be clear that the de nition imposes no constraint on the type
of objects that may constitute a set. Thus,
A = f ; x2 2 = 0; Galapagosg

39
40 CHAPTER 3. SETS AND FUNCTIONS

is a legitimate set, consisting of three elements | a symbol, an equation,


and a name. Equally legitimate is a set containing another set as an ele-
ment. For instance,
B = fa; fa; bgg

contains two elements, namely a and the set fa; bg. In particular,
a2B b 62 B fb; ag 2 B:
The empty set is the set that does not contain any element. This set is
important in the formal development of the theory and is denoted by the
symbol ;. Formally
; = fg:
The number of elements of a set A | called the cardinality of A | is
denoted by jAj.
jfa; b; abgj = 3: jffa; bggj = 1 jfgj = 0:
Example 3.1. Some nite sets.
1. The set D(n) of divisors of a positive integer n
D(120) = f1; 2; 3; 4; 5; 6; 8; 10; 12; 15; 20; 24; 30; 40; 60; 120g
D(127) = f1; 127g: (3.1)
2. The set P (n) of all partitions of a positive integer n | the possible
ways of representing n as a sum of positive integers, ignoring the order
of the summands
P (5) = f5; 4+1; 3+2; 3+1+1; 2+2+1; 2+1+1+1; 1+1+1+1+1g:

3. The set C (n) of all parenthesised expressions that evaluate to the


product of n objects a1 a2    an
C (4) = fa1 (a2 (a3 a4 )); a1 ((a2 a3 )a4 ); (a1 a2 )(a3 a4 );
(a1 (a2 a3 ))a4 ; ((a1 a2 )a3 ) a4 g:
Example 3.2. Some in nite sets.
1. The set of primes
 = f2; 3; 5; 7; 11; : : : g (3.2)
2. The set n of primes that give remainder 1 when divided by n, for
n>1
4 = f5; 13; 17; 29; 37; : : :g: (3.3)
3.1. SETS 41
3. The set nZ of the multiples of a nonzero integer n
6Z = f: : : ; 12; 6; 0; 6; 12; : : : g: (3.4)
Note that nZ = nZ.
4. The set n of positive integers relatively prime to an integer n > 1
6 = f1; 5; 7; 11; 13; : : : g:
5. The set of squares in Z
f0; 1; 4; 9; 16; 25; : : : g:
6. The set Z[1=n] of rationals whose denominator is a power of a positive
integer n. For example, the rational 127=128 = 127=27 belongs to
Z[1=2] while 128=127 does not.
7. The set n of all words made of n letters, for n > 0
2 = fa; b; aa; bb; ab; ba; aaa; aab; : : : g: (3.5)
8. The set of Pythagorean triples (see end of section 2.4)
f(4; 3; 5); (12; 5; 13); (8; 15; 17); : : : g:
Example 3.3. Some sets whose status ( nite vs. in nite) is not known.
1. The set T of twin primes, i.e., the set of pairs (x; x + 2) where both
x and x + 2 are prime

T = f(3; 5); (5; 7); (11; 13); (17; 19); (29; 31); (41; 43); : : : g: (3.6)
The largest known twin primes (as of December 2000) are
665551035  280025  1
with 24099 digits.
2. The set of Mersenne numbers Mp = 2p 1, p prime, which are prime
fM2; M3 ; M5; M7 ; M13 ; : : : g:
3. The set of Mersenne numbers which are not prime
fM11 ; M23 ; M29; M37 ; : : : g:
42 CHAPTER 3. SETS AND FUNCTIONS

In the above examples, the sets were de ned by listing the distinctive
properties of their elements. We develop a notation for this type of de ni-
tion. For instance, let A be the set of of non-negative powers of 2
A = f1; 2; 4; 8; 16; 32; 64; 128; 256; : : : g:

We write
A = fm m = 2k and k 2 N g:
The symbol before the vertical bar represents a generic element of the set.
After the vertical bar, we list the properties that every element of the set
must satisfy. The symbol before the bar may be replaced by an expression,
resulting in greater conciseness
A = f2k k 2 N g:

If every element of A is an element of B , we say that A is contained in


B or is a subset of B , and we write A  B . It then follows that for any
set A we have A  A, and ;  A. Every subset of A which is not A or
; | if it exists | is called a proper subset. If A  B and B  A, then
A = B . If A  B but A 6= B , then we write A  B . (You should think of
the relational operators  and  as being the set equivalent of  and <,
respectively.) The power set P (A) of a set A is the set of all its subsets,
proper and improper
P (fa; b; cg) = ffg; fag; fbg; fcg; fa; bg; fa; cg; fb; cg; fa; b; cgg:
The relation A  B is spelled out formally as
x 2 A =) x 2 B (3.7)
where the symbol =) reads `implies' or | more mathematically | `only
if'. Expression (3.7) says that the property on the left-hand side of the
arrow (the element x belongs to the set A) is true only if the property
on the right-hand side (the element x belongs to the set B ) is true. This
suggests an alternative way of writing (3.7), namely,
x 62 A (= x 62 B

where (= now reads `if'. Note that reversing the implication requires
negating the operator 2, that is, changing the logical value of both expres-
sions (think about it).
Similarly, if B  A we write
x 2 A (= x 2 B: (3.8)
It should be clear that the relations A  B and B  A are not mutually
exclusive. If (3.7) and (3.8) hold simultaneously, we have
x 2 A () x 2 B
3.1. SETS 43
which says that x is in A `if and only if' x is in B . The two statements
are equivalent: they are either both true or both false. This is the formal
de nition of equality between sets (A = B ).
We now introduce operations between sets, de ned in terms of the no-
tion of membership to a set. These operations are binary , in that they
involve two sets at a time, in much the same way as the arithmetical oper-
ations between numbers.
Union
The union of two sets A and B , denoted by A [ B , is the set constituted
by those elements that belong to at least one of the two sets A and B . In
particular, the union includes the elements that belong to both.
x 2 A[B () x 2 A or x 2 B: (3.9)
The conditions on the right-hand side, when taken individually, give two
one-way implications
x 2 A[B (= x 2 A
x 2 A[B (= x 2 B:
Intersection
The intersection of two sets A and B , denoted by A \ B , is the set consti-
tuted by those elements that belong to both A and B .
x 2 A\B () x 2 A and x 2 B: (3.10)
We have two one-way implications
x2 A\B =) x 2 A
x2 A\B =) x 2 B:
Di erence
The di erence of B from A, denoted by A n B , is the set of the elements of
A that do not belong to B .

x 2 AnB () x 2 A and x 62 B: (3.11)


We have two one-way implications
x 2 AnB =) x 2 A
x 2 AnB =) x 62 B:
Example 3.4. Let A = fa; b; cg and B = fa; c; d; eg. We have A [ B =
fa; b; c; d; eg, A \ B = fa; cg, A n B = fbg, and B n A = fd; eg.
44 CHAPTER 3. SETS AND FUNCTIONS

Example 3.5. Let A  B . Then A [ B = B , A \ B = A, and A n B = ;.


Example 3.6. Let N e be the set of even natural numbers and N o that
of odd natural numbers. Then N e [ N o = N , N e \ N o = ;, N e n N o = N e ,
No n Ne = No .
Example 3.7. With reference to (3.2) and (3.3), we have that
 = 2 [ f2g:
Example 3.8. For any nonzero integers m and n we consider the sets
mZ and nZ, de ned in (3.4). Every element of nZ \ mZ is a multiple of
both n and m, and every multiple of n and m is an element of nZ \ mZ.
Therefore, this set contains the least common multiple of n and m. But
it cannot contain any smaller positive integer, from the de nition of least
common multiple. So we have
mZ \ nZ = lcm(m; n)Z:
Example 3.9. Consider the set D(n) of the divisors of n (see (3.1)). Then
the common divisors of m and n constitute the set D(m) \ D(n). Because
every divisor of m and n is a divisor of their greatest common divisor, we
have
D(gcd(m; n)) = D(m) \ D(n):

Exercises
Exercise 3.1. Prove that for any two sets A and B , the following holds
A \B A A \B B A \ B  A [ B:
Exercise 3.2. Let S and C be the sets of squares and cubes of natural
numbers, respectively.
S = f0; 1; 4; 9; 16; : : :g C = f0; 1; 8; 27; 64; : : :g
Characterize S \ C in terms of the prime factorization of its elements.
Exercise 3.3. Show that the set of primes p such that p +2 and p 2 are
also primes has only one element. (Hint: if p is prime, then one of p + 2 or
p 2 is divisible by 3.)
Exercise 3.4 .
 Let A, B , and C be arbitrary sets. Prove that (i) A [ (B [
C ) = (A [ B ) [ C (associative law for unions); (ii) A \ (B \ C ) = (A \ B ) \ C
(associative law for intersections); (iii) A \ (B [ C ) = (A \ B ) [ (A \ C )
(distributive law).
3.2. SETS WITH MAPLE 45
3.2 Sets with Maple
Maple supports the set data type, with straightforward syntax. The fol-
lowing assignment statement de nes a set of 3 integers
> T:=f1,3,-4g;

T := f1; 3; 4g

> whattype(%);

set

A set is an example of a composite data type, which can consist of an


arbitrary number of operands. Maple eliminates repeated elements in a set
> f7,7,0,3,7g;

f7; 0; 3g
and may rearrange the order of the elements
> f-4,3 1g;

f1; 3; 4g
To check whether or not a given element belongs to a set, we use the
standard library function member, which returns a value of the logical type
> U:=fa,fa,bgg:
> member(a,U),member(b,U),member(fb,ag,U);

true; f alse; true

The empty set ; is represented in Maple by the curly brackets alone


> empty:=fg;

empty := fg
To count the number of elements of a set, we use the function nops (number
of operands)
> nops(U),nops(empty);

2; 0
46 CHAPTER 3. SETS AND FUNCTIONS

Set operators
Maple supplies three set operators, namely union, intersect, and minus,
for union, intersection, and di erence between sets, respectively (see (3.9),
(3.10), and (3.11)). Their straightforward syntax is illustrated in the fol-
lowing examples.
> A:=f1,f1,2gg;
A := f1; f1; 2gg

> B:=f1,f1,3gg;
B := f1; f1; 3gg

> A union B;
f1; f1; 2g; f1; 3gg
> A intersect B;
f1g
> A minus B;
ff1; 2gg
> B minus A;
ff1; 3gg
Logical operators
Sets are often de ned through set operations. For instance, let a and b be
rationals such that a < b. The rational interval [a; b) containing the left
endpoint a but not the right endpoint b is the intersection of two sets A
and B , given by
A = fx 2 Q x  ag B = fx 2 Q x < bg:

Now, from the de nition (3.10) of the intersection of two sets, we may say
that x belongs to [a; b) = A \ B , when the proposition x 2 A is true and the
proposition x 2 B is true. Accordingly, we shall test the condition x 2 [a; b)
with Maple through the truth or falsehood of the logical expression
> x >= a and x < b;
The union of two sets would require a similar construct, with the term `and'
replaced by `or', whereas the di erence between A and B would read x 2 A
and (not x 2 B ).
The binary logical operators and and or, and the unary logical operator
not, relate expressions whose value is of the logical (Boolean) type. These
operators act on the set B = ftrue; f alseg of the two Boolean constants.
(Maple actually has a three-way logic, involving the additional Boolean
constant FAIL, but we shall ignore it for the time being.) They should be
3.2. SETS WITH MAPLE 47
thought as an analogue of the binary arithmetical operators + and , and
the unary operator (sign change, carrying x to x), respectively, which
combine, for instance, elements of Z and Q .
The action of the binary operators and and or and of the unary operator
not is de ned by listing all possibilities:

LOGICAL OPERATORS

x y x and y x or y not x

false false false false true


true false false true false
false true false true true
true true true true false

Thus, x and y is equal to true only if both operands are equal to true,
while for x or y to be equal to true, only one of the operands needs to have
the value true. The following properties of logical operators can be veri ed
directly from the entries of the above table
(i) x and y = y and x
(ii) x or y = y or x
(iii) not (x and y) = (not x) or (not y)
(iv) not (x or y ) = (not x) and (not y )

The rst two properties state the commutativity of the operators and and
or, which in this respect behave just like + and .
Maple implements logical operators and expressions in a straightforward
manner. If there are several operators in a logical expression, they are
evaluated in the following order, given by: rst not, then and, then or.
Parentheses may be used to alter the order of evaluation. Expressions
containing logical operators are identi ed by Maple as being of the logical
type, and evaluated automatically. When this is the case, the use of evalb
is no longer required.
In the following examples we combine logical operators with relational
expressions:
Example 3.10. We verify property (iii) above, for the values x = true; y =
f alse
> not (true and false) = (not true) or (not false);
true

Example 3.11. Let A = f1; 2; 3g and B = f2; 3; 4g. We verify that


4 2 B n A in two ways, using the two equivalent de nitions (3.11)
48 CHAPTER 3. SETS AND FUNCTIONS

> A:=f1,2,3g: B:=f2,3,4g:


> member(4, B minus A), member(4,B) and not member(4,A);
true; true

Example 3.12. Verify that 83 divides 341 1, but it does not divide
241 1.
> not irem(2^41-1,83)=0 and irem(3^41-1,83)=0;
true
Even if the relational operator = is involved, the presence of the logical
operators makes the Boolean status of the above expression unequivocal,
so that Maple evaluates it automatically without the need of calling evalb.
Example 3.13. Verify that the integer n = 10042 + 1 is a prime of the
form 7k + 3 or 7k + 4, for some integer k. We have to test n for primality
and check that n gives remainder 3 or 4 when divided by 7.
> 1004^2 + 1:
> isprime(%) and (irem(%,7)=3 or irem(%,7)=4);
true

The last expression requires two evaluations of irem(%,7). One of the two
can be avoided as follows
> isprime(%) and member(irem(%,7),f3,4g);

Exercises
Exercise 3.5. Without displaying any digit, verify that 11396333 is di-
visible by 43 or 47, but not by both.

3.3 Functions
Let A and B be two sets. By a function f de ned on A with values in B
we mean a rule which associates to every element x of A one | and only
one | element of B , denoted by f (x). We write
f :A!B f := x 7! f (x): (3.12)
The set A is called the domain of f , and the set B the co-domain (or range).
The clause that f (x) be unique is crucial: this is what makes functions
interesting. Also, a function must be de ned for all elements of the domain
A. If this is not the case, then A cannot be called the domain of the
function. In other words, the domain is always chosen as economically as
possible: it has no redundant elements.
As x varies in the domain A, f (x) varies in the co-domain B , and the
set of elements of B that can be obtained in this way is called the image
3.3. FUNCTIONS 49
of A, denoted by f (A). Because every element of f (A) is in B , we have
f (A)  B , but the de nition of a function does not require that f (A) be
equal to B , that is, that the image must coincide with the co-domain. So,
unlike the domain, the co-domain of a function can be | and often is |
chosen with redundant elements.
If the image coincides with the co-domain, we say that f is surjective
(or onto ). Then, for every element y of B there exists at least one element
x of A such that f (x) = y . It immediately follows that any function f can
be turned into a surjective function if we identify co-domain and image:
f : A ! f (A).
If distinct elements of A always have distinct images in B , then f is said
to be injective (or one-to-one). Thus, a function is injective if f (x) = f (y)
implies x = y, for all x and y in the domain. If the domain of f is nite, then
f is injective precisely when domain and image have the same cardinality
(think about it).
A function which is both injective and surjective is said to be bijective.
A bijective function establishes a strong correspondence between domain
and co-domain.
Example 3.14. On any set A, we de ne the identity function, given by
IA : A ! A IA := x 7! x:

The identity function is bijective, and its domain, co-domain, and image
all coincide with A.
Example 3.15. Let
A = f 2; 1; 0; 1; 2g B = f 4; 3; 2; 1; 0; 1; 2; 3; 4g

and
f :A!B f := x 7! 2x:
Then f (A) = f 4; 2; 0; 2; 4g, so that the image is distinct from the co-
domain and f is not surjective. For instance, 3 2 B , but there is no
element x of A such that f (x) = 3. Because the domain of f is nite,
and the image has the same cardinality as the domain, we conclude that f
is injective without further check.
Example 3.16. The function g := x 7! x , with domain and co-domain
2
as in the previous example, is neither injective nor surjective. Indeed,
jAj = 5 and jg(A)j = 3, so g is not injective (for instance, 1 and 1 are
distinct elements of A but g( 1) = g(1) = 1 is the same element of B ).
Likewise, 1 62 g(A), so g is not surjective.
Example 3.17. Let
A = f0; 1; 2; 3; 4g B = f0; 2; 4; 6; 8g

and
f :A!B x 7! rem(6x; 10):
50 CHAPTER 3. SETS AND FUNCTIONS

Thus, f (0) = 0, f (1) = 6, f (2) = 2, f (3) = 8, and f (4) = (4). This


function is bijective.
Example 3.18. Consider the following function

x+1
f : Z n f0g ! Q f := x 7! : (3.13)
x
Division by zero requires that the integer x = 0 be excluded from the
domain of f , for otherwise we would have to set f0 = 1, but this value is
not a rational number. Alternatively, one could adjoin the point x = 1 to
the co-domain of f , and extend the de nition of f to x = 0 as follows:
x + 1 if x 6= 0,


f : Z! Q  f := x 7! x
1 if x = 0
where Q = Q [f1g. With either de nition, the function f is injective. We
prove it for the case (3.13). If f (x) = f (y), then (x +1)=x = (y +1)=y, and
because x and y are nonzero, we have xy + y = xy + x, whence x = y. On
the other hand, f is not surjective. For instance, the rational 3 does not
belong to the image f (Z), because the equation f (x) = 3 yields x = 1=2,
which is not in the domain Z.
Example 3.19. Let S be the set of squares of elements of N
S = f02 ; 12 ; 22 ; 32 ; 42 ; 52 ; : : : g:

We de ne the square root function as follows


p:S!N p := x 7! y; where y2 = x:
The integer y = px is uniquely de ned by x, because we have taken the
precaution of excluding the negative integers from the co-domain. There-
fore, if one keeps the above de nition, the co-domain of the square root
cannot be extended to Z, because to every x in S there would correspond
two elements of Z, contradicting the de ning property of a function.
Example 3.20. Let  be the set of primes. We de ne

p if p + 2 2 
n
 :  !  [ f0g p 7!
0 otherwise.
The function  is neither injective nor surjective, which can be seen, for
instance, from the fact that  (2) =  (7) = 0: two elements of the domain
have the same image, and neither of them belongs to  (). The set  ()
consists of 0 and a representative for each pair of twin primes; see (3.6).

3.4 User-de ned functions


In Maple, it is possible to de ne new functions, to be used alongside the
library functions. They are the user-de ned functions. The simplest such
3.4. USER-DEFINED FUNCTIONS 51
construction makes use of the arrow operator ->. For example, the function
de ned in (3.13) is constructed in Maple as follows
> f:=x->(x+1)/x;
f := x ! x +x 1
This is a new data type
> whattype(%);
procedure

Once a new function is de ned, it can be used like any other library function,
by substituting any valid expression for its argument. In our example, valid
expressions are arithmetical and algebraic expressions
> f(2/3),f(joe),f(a^2-1);
5 ; joe + 1 ; a2
2 joe a2 1
We make some syntactical remarks.
The name of the function's argument (the variable appearing immedi-
ately on the left of the arrow operator) is invisible from the outside, and in
particular, it is unrelated to any variable with the same name that could
have been previously de ned. Study the following example carefully:
> g:=n->2*n:
> h:=whatever->2*whatever:
> whatever:=3:
> g(2),h(2),g(whatever),h(whatever),g(n),h(n);
4; 4; 6; 6; 2n; 2n
Common mistakes originate from assignments such as
> wrong(x):=2*x+1:
This statement does not de ne a Maple procedure, in spite of the fact that
it is syntactically legal. Thus,
> wrong(x),wrong(2),wrong(1/y);
2x + 1; wrong(2); wrong y1
 

One sees that Maple knows what is wrong(x), but nothing else (this feature,
which allows a function to be de ned at individual values of the argument,
is useful in the so-called recursive de nitions).
In the above construct, the value assigned to the variable f is a pro-
cedure de nition: x ! (x + 1)=x. However, for reasons of eÆciency of
computation, the function's symbolic name is not evaluated automatically
(the function's name is a pointer to the place in memory where its value is
stored)
52 CHAPTER 3. SETS AND FUNCTIONS

> f,whattype(f);
f; symbol

To force evaluation, one must use the intrinsic function eval


> eval(f),whattype(eval(f));
x ! x +x 1 ; procedure
Results analogous to a procedure de nition can also be obtained via
substitutions in an expression, although this is often clumsier and less trans-
parent.
> f:=(x+1)/x;
f := x +x 1
> subs(x=2/3,f),subs(x=joe,f),subs(x=a^2-1,f);
5 ; joe + 1 ; a2
2 joe a2 1
Finally, a ne point of mathematical notation is noted. The arrow oper-
ator -> corresponds to the mathematical symbol 7! for function de nition
| see equation (3.12). However, Maple displays it as !, which has a
di erent meaning, namely that of specifying domain and co-domain.
Characteristic functions and the if-structure
Let A be a set, and let C be a subset of A. The function
1 if x 2 C


C : A ! f0; 1g x 7! (3.14)
0 if x 62 C
is called the characteristic function of C in A. A variant of the above
construction is the Boolean characteristic function, given by
if x 2 C


C : A ! ftrue; f alseg x 7!
true
f alse if x 62 C .
(3.15)
Example 3.21. For a non-empty set A the following holds
; (A) = f0g A (A) = f1g:

So if C is an improper subset of A (i.e., C = A or C = ;),  fails to be


surjective. On the other hand, let C be a proper subset of A. Because C is
not empty, it has at least one element, whence C (A) contains 1. But since
C 6= A, there exists at least one element of A which is not in C , whence
C (A) contains 0. Therefore, the characteristic function C is surjective if
and only if C is a proper subset of A.
The evaluation of the characteristic function (3.14) or (3.15) requires a
process of decision-making: we have to decide whether or not the element x
3.4. USER-DEFINED FUNCTIONS 53
belongs to the set C , and then assign the value to the function  accordingly.
The Boolean case is simpler, since the values true or f alse can be obtained
by evaluating a Boolean expression. If the set C is given explicitly, then
C (x) will be represented in Maple by the expression member(x,C). If C
is de ned by a certain property, then one will translate the latter into a
Maple logical expression, and then adopt a construct of the type
> chi:=x->logical expression;
which may or may not require the use of evalb.
Example 3.22. Let n be an integer. We construct the function even(n)
whose value is true if n is even, and f alse if n is odd. This is the Boolean
characteristic function of 2Z in Z.
> even:=n->evalb(irem(n,2)=0):

Example 3.23. We consider the interval [0; 1) in Q consisting of all ra-


tionals between 0 and 1 (the left endpoint 0 is included, the right endpoint
1 is not). Its Boolean characteristic function is given by
> interval:=x->x >= 0 and x < 1:
Note that evalb is unnecessary here, since the presence of the logical op-
erator and makes the logical status of the expression unambiguous.
In the non-Boolean case (3.14), the decision-making is implemented in
Maple by the if-structure. Its simplest form is the following:
> if logical expression then expression 1 else expression 2 fi:
If the value of logical expression is true then expression 1 is executed; if it
is false, then expression 2 is executed.
Two syntactical remarks. First, the evaluation of the logical expression
is done automatically; that is, there is no need to use evalb. Second, the
statements need not be followed by a terminator (colon or semicolon). This
is because an if-statement is logically equivalent to a single statement. We
shall deal with the if-structure in greater generality in chapter 9. Here we
are mainly interested in its applications to the construction of characteristic
functions.
Example 3.24. Consider the characteristic function of the subset f0g of
Z (cf. (3.14)).


 : n 7!
1 if n = 0 (3.16)
0 if n 6= 0.
The Maple implementation is straightforward:
> chi:=n->if n=0 then 1 else 0 fi:
The Boolean version of the same function is even simpler, as it does not
require the if-structure
> chi:=n->evalb(n=0);
54 CHAPTER 3. SETS AND FUNCTIONS

Example 3.25. The Boolean characteristic function of the set of primes


is given by isprime. Its non-Boolean version is then constructed as
> chi:=n->if isprime(n) then 1 else 0 fi:

Example 3.26. We consider the characteristic function of Z in Q


1 if x 2 Z


 : Q ! f0; 1g  : x 7!
0 if x 62 Z.
We note that a rational x is an integer precisely when its denominator is
equal to 1. Thus,
> chi:=x->if denom(x)=1 then 1 else 0 fi:

Example 3.27. To illustrate a more general usage of the if-structure,


we construct the function nint(x), which returns the integer nearest the
positive rational x. If the fractional part of x = a=b does not exceed 1=2,
the nearest integer is the quotient of the division of a by b; otherwise, it is
the same quantity plus one.
> nint:=x->if 2*irem(numer(x),denom(x))<=denom(x) then
> iquo(numer(x),denom(x))
> else
> iquo(numer(x),denom(x))+1
> fi:
To improve readability, we have subdivided the expression over several lines
of input. The above version of nint has two shortcomings: rst, it gives the
incorrect answer when the argument is negative, and second, it is ineÆcient
in that the functions irem and iquo perform essentially the same calculation
(see remarks at the end of section 2.7). To solve these problems we shall
require a more general form of procedure, discussed in section 9.4.
Functions of several variables
The arrow operator construction can be generalized to the case of functions
of several variables. The formal aspect of this construction will be dealt with
in chapter 9. Here it suÆces to note that a function of several variables
is a rule that associates to a sequence (x1 ; x2 ; : : : ; xn ) of n elements of
the sets A1 ; : : : ; An a unique element of another set, which we denote by
f (x1 ; x2 ; : : : ; xn ). In Maple, the sequence of variables must be enclosed
within round brackets.
Example 3.28. A function depending on a parameter. Let a be an inte-
ger, and let us consider the function
fa : Z ! Z fa := x 7! ax:

Every value of a corresponds to a di erent function. If a = 0 the image of


fa is the set f0g, and fa is neither injective nor surjective. If a 6= 0, the
3.4. USER-DEFINED FUNCTIONS 55
image of Z under fa is the set of multiples of a, that is, the set of all integers
that are divisible by a. If jaj = 1, then fa(Z) = Z, and fa is bijective. For
a = 1, fa is the identity function on Z. If jaj > 1, fa is injective but not
surjective. Convince yourself that for any value of a, fa(Z) = f a (Z). To
represent this function with Maple, we think of it as a function of the two
variables a and x
> f:=(a,x)->a*x;
f := (a; x) ! a x
> f(3,k),f(3,3);
3k; 9
Example 3.29. We construct the characteristic function of the set dZ
of the integer multiples of a nonzero integer d, de ned in (3.4). This is a
function of the two variables x and d, where d is regarded as given, while x
assumes any integer value. Using the fact that irem(x,d) is zero precisely
when n is a multiple of d, we have
> Multd:=(x,d)->if irem(x,d)=0 then 1 else 0 fi:

Example 3.30. We construct the characteristic function Divs(x,n) of


the set of divisors (positive or negative) of a given nonzero integer n in Z.
We begin with a preliminary de nition:
> Divs:=(x,n)->if irem(n,x)=0 then 1 else 0 fi;
As for Multd, the construction is based on irem, with the role of the vari-
ables interchanged. This time, the rst variable n is xed, while the second
one is allowed to vary in the domain 1  jxj  n. The following alternative
de nition makes the relationship between the two functions explicit.
> Divs:=(x,n)->Multd(n,x):
If the rst argument of Divs is equal to zero, we get an error termination,
because the second argument of irem cannot be zero. On the other hand,
it would be desirable to allow zero as a legal rst argument, in which case
Divs should return the value zero. This can be achieved as follows
> Divs:=(x,n)->if not x=0 and irem(n,x)=0 then 1 else 0 fi:
The logical expression de ning Divs is evaluated left to right, and if x = 0
the relational expression not x=0 evaluates to f alse. Maple knows that
the entire logical expression is then f alse, so the relational expression
irem(n,x)=0 is not evaluated at all. Note that the logically equivalent
construct
> Divs:=(x,n)->if irem(n,x)=0 and not x=0 then 1 else 0 fi:
would not work, because in this case, Maple evaluates irem(n,x) before
checking that x is nonzero.
56 CHAPTER 3. SETS AND FUNCTIONS

Mapping all elements of a set


The image f (A) of a set A under a function f was de ned as the set obtained
applying f to all elements of A. The image of a set can be constructed in
Maple with the standard library function map.
In the following example, we construct the image of the set f 2; 1; 0; 1;
2g under the function f : x 7! x2
> A:=f-2,-1,0,1,2g:
> f:=x->x^2:
> map(f,A);
f0; 1; 4g
The rst argument of map is an expression of the procedure type (a function
de nition), while the second is a set. (In chapter 5 we shall see that map
accepts any expression as a second argument, not just a set.) Because the
value of the variable f is x->x^2, such expression can be used explicitly,
without de ning the function separately
> map(x->x^2,A);

Example 3.31. Let A = f0; 1; 2; 3; 4; 5g. We show with Maple that the
mapping f : x 7! rem(x + 5; 6) of A to itself is bijective. Because domain
and co-domain are the same, it suÆces to check that A = f (A).
> f0,1,2,3,4,5g;
> evalb(map(x->irem(x+5,6),%)=%);
true

Example 3.32. Let A be a set of integers. We construct a function which


returns true if A contains a prime, and f alse otherwise.
> ContainsPrimes:=A->member(true,map(isprime,A)):
The expression map(isprime,A) is the image of A under the function
isprime. If there is a prime in A, then such image contains the element
true, which is the test performed by the function member.
If the rst argument of map is a function of several variables, then the
value of all variables beyond the rst one must be supplied in the form of
a sequence of optional arguments. We illustrate this construction in the
following examples.
Example 3.33. Let A be a nite set of integers, and let n be any integer.
Then the value of the expression map(igcd,A,n) is the set constituted by
the greatest common divisors of n and each element of A.
Example 3.34. Let A be a set of integers, and let d be a nonzero integer.
We construct a function mapping A to the set of rationals obtained by
dividing each element of A by d.
> DivBy:=(A,d)->map((x,y)->x/y,A,d):
3.4. USER-DEFINED FUNCTIONS 57
Exercises
Exercise 3.6. Construct a user-de ned function for the function h(a) =
a2 + a 1. Use this function to compute the following expressions
52 + 5 1 32 3 1 b4 + b2 + 1
1 1 1
(x + 1)2 + x + 1 1 Z6 + Z3
(114 1)2 114:
Exercise 3.7. Let A = f1; 2; 3g and B = f0; 1g.

(a) Determine the number of distinct surjective functions f : A ! B .


(b) Construct three distinct user-de ned surjective functions f : A ! B
[Hint: use irem, iquo, abs, etc.].
(c) Using one of the functions f constructed above and map, verify directly
that f is surjective.
Exercise 3.8. Construct user-de ned functions for the following charac-
teristic functions
(a) f (x) = 10 ifotherwise
x is negative
n

Use f to decide whether or not 5002 89  532 is negative.

( ) = 10 ifotherwise
x is a multiple of 7
n
(b) f x

Use f to decide whether or not 1002 + 982 is divisible by 7.

( ) = 10 ifotherwise
x and x + 2 are prime
n
(c) f x

Use f to decide whether or not p105 p104 = 2, where pk is


the kth prime. (Think about it.)
(d) f (x; y ) =
n
1 if x and y are relatively prime
0 otherwise
Use f to decide whether or not the prime 2999 divides 9! 1.
Exercise 3.9. Construct the Boolean characteristic function of the fol-
lowing sets. Use evalb only if necessary.
(a) The set of even non-negative integers.
(b) The set of rationals whose numerator is odd.
(c) The set of rationals whose denominator is composite.
(d) The set of primes which are twice a prime plus one.
(e) The set of integers which are divisible by 5 or by 7, but not by both.
58 CHAPTER 3. SETS AND FUNCTIONS

(f ) The set of positive integers i for which the ith prime is twice a
prime plus one; hence compute the intersection between such set and the
set f101; 102; 103; 104; 105g.
Exercise 3.10. Let n be a positive integer. Construct a function nearp(n)
whose value is the prime number nearest n.
Exercise 3.11. Let r and s be positive rational numbers. Construct a
function K(r,s) whose value is true if there is an integer between r and s,
and f alse otherwise. (You may assume that r and s are not integers.)
Chapter 4

Sequences
Sequences are functions de ned over the integers. The ordering property
of the integers is what makes sequences special.

4.1 Basics
When the domain of a function is the set of positive integers N + , one speaks
of a sequence. Thus, a sequence f is a rule which associates to every positive
integer n a unique element f (n) of a given set B . For instance, let B = Z,
and let us consider the function f which associates to every natural number
n the value of the expression 2n n2 . We write
f : N+ ! Z f := n 7! 2n n2
or, more compactly
f (n) = 2n n2 n  1: (4.1)
The elements of this sequence are the integers f (1); f (2); f (3); : : : = 1; 0;
3; : : : . When a function is a sequence, it is customary to write fn in place
of f (n). So we write out the elements of the sequence as
f1 ; f2 ; f3 ; : : : ; fk ; : : :
and the entire sequence as ffk g, or, more pedantically, ffk g1 k=1 . In the
above notation, f is a function, k is an element of the domain of f , fk is
an element of the co-domain of f , and ffk g is the image (think about it).
The condition that the domain of a sequence be N + may be relaxed.
For instance, it may be convenient to restrict the domain to a proper subset
of the positive integers, or to extend it to the natural numbers N , or even
to the whole of Z. In the latter case, we speak of a doubly-in nite sequence
: : : ; a 2 ; a 1 ; a0 ; a1 ; a2 ; : : :
59
60 CHAPTER 4. SEQUENCES

For instance, the sequence of odd integers is doubly-in nite.


Example 4.1. Let us consider the following sequence of rational numbers
1
a : n 7! 2 : (4.2)
n 3n + 2
Factoring the denominator n2 3n + 2 = (n 1)(n 2), we see that (4.2)
is unde ned for n = 1; 2 when the denominator vanishes and an becomes
in nite. Accordingly, we restrict the domain of a to the subset of N + given
by n  3, which is N + n f1; 2g. Alternatively, we may perform the change
of variables n = m 2. Then the inequality n  3 becomes m  1, and
(4.2) is transformed into a new sequence de ned over the whole of N +
1 1
b(m) = = 2 m  1:
(m 2)2 3(m 2) + 2) m 7m + 12
It should be clear that bk = ak+2 for all k  1.
It must be stressed that the co-domain B that contains the elements of
a sequence, as well as the nature of the rule associating an element of B
to every positive integer, is completely arbitrary. In particular, one should
not assume that the computation of f (n) merely requires substituting the
value of n in some expression
f := n 7! an expression depending on n n  1: (4.3)
This is just the simplest possibility, and the sequences constructed in this
way form a small class among all sequences.
Example 4.2. We consider the sequence generated by the Boolean char-
acteristic function of the set of primes in N + :

p := n 7! true if n is prime
false if n is not prime n  1: (4.4)

The elements of such a sequence belong to the set ftrue; falseg: the rst
few of them are
false; true; true; false; true; false; true; false; false; false; : : :
Even though the function p is represented explicitly by the function isprime,
the process that allows Maple to determine whether p(n) is true or false
is complicated. In spite of some 2000 years of e ort, nobody has yet suc-
ceeded in reducing this algorithm to the evaluation of a simple `formula'.
If you test isprime on large values of n, you will notice how much Maple
struggles to give you the answer.
4.2. SEQUENCES WITH MAPLE 61

4.2 Sequences with Maple


A sequence de ned explicitly (see (4.3)) can be represented in Maple by
any function taking integers as arguments. Such function may be a Maple
library function, or one de ned by the user. In either case, there is a
straightforward way of generating its elements, with the Maple intrinsic
function seq. The following command generates the rst 10 prime numbers,
by making use of the standard library function ithprime.
> seq(ithprime(k),k=1..10);
2; 3; 5; 7; 11; 13; 17; 19; 23; 29
The intrinsic function seq has two arguments. The rst is the Maple ex-
pression ithprime(k), while the second speci es the variable k, as well as
the list of integers from 1 to 10. The variable k is sequentially assigned
each value in the list, which is in turn substituted into the rst expression.
So the above seq command is equivalent to the sequence of expressions
ithprime(1),ithprime(2),...,ithprime(10).
Example 4.3. Generate the elements p100 ; : : : ; p110 of the sequence (4.4).

> seq(isprime(k),k=100..110);

false; true; false; true; false; false; false; true; false; true; false
Thus, 101, 103, 107, and 109 are prime.
Example 4.4. Generate the rst 10 elements of the sequence

k+1
f : k 7! 2 k  1:
k
We construct a user-de ned function for f .
> f:=k->(k+1)/k^2:
> seq(f(n), n=1..10);
3 4 5 6 7 8 9 10 11
2; ; ; ; ; ; ; ; ;
4 9 16 25 36 49 64 81 100
Example 4.5. Generate the set S of the rst 30 non-negative powers of
2.
> S:=fseq(2^i, i=0..29)g;
S := f1; 2; 4; 8; 16; 32; 64; 128; 134217728; 268435456; 536870912;
256; 512; 1024; 2048; 4096; 8192; 16384; 32768; 65536;
131072; 262144; 524288; 1048576; 2097152; 4194304;
8388608; 16777216; 33554432; 67108864g
While the expression sequence produced by seq was in the appropriate
order, the enclosure between curly brackets has resulted in a seemingly
arbitrary arrangement of the elements of the set.
62 CHAPTER 4. SEQUENCES

The seq command has the syntax seq(e,i=a..b), where e is any ex-
pression, i is a name, and a and b are expressions which must evaluate to
an integer. The expression a..b is of the range type
> whattype(a..b);
::
Before executing seq, Maple expands the range expression, which evaluates
to a sequence of integers. This can be done explicitly with the sequence
operator $
> $1..10;
1; 2; 3; 4; 5; 6; 7; 8; 9; 10
(The range a..b may also be replaced by more general expressions | see
chapter 6.)
The value of seq is a list of expressions separated by commas, called an
expression sequence, or, more brie y, a sequence. The following command
generates a sequence of sets
> seq(f$1..ng,n=0..4);
fg; f1g; f1; 2g; f1; 2; 3g; f1; 2; 3; 4g
> whattype(%);
exprseq
Unlike the elements of a set, the elements of an expression sequence are
arranged in a prescribed order. If in the range a..b the value of a is
greater than that of b, the result is the NULL sequence. NULL sequences
may be de ned explicitly, which is useful in initializations
> s:=NULL;
s :=
> s:=s,1,2,3;
s := 1; 2; 3
Example 4.6. We construct a function divs(n) whose value is the set of
divisors of a positive integer n (see also ?divisors). A straightforward (if
ineÆcient) approach consists in applying the function x 7! gcd(x; n) to the
set of the rst n positive integers. The latter is constructed by expanding
the range 1..n with the operator $. The mapping is performed with the
function map, whose rst argument is igcd. Because igcd is a function of
two variables, the second variable must be supplied as the third argument
of map.
> divs:=n->map(igcd,f$1..ng,n):
> divs(84);
f1; 2; 3; 4; 6; 7; 12; 14; 21; 28; 42; 84g
4.2. SEQUENCES WITH MAPLE 63

Evaluating this function requires n calls to the function igcd. We now


consider improvements in the eÆciency of computation. Apart from the
trivial divisors 1 and n, all other divisors of n lie between 2 and n=2, so we
can save half of the evaluations of igcd
> divs:=n->map(igcd,f$2..iquo(n,2)g,n) union f1,ng:
A more substantial improvement is achieved by computing the divisors d
pn, and
between 2 and
p then pairing each of them with its twin divisor n=d.
To compute n, we use the integer square root function isqrt.
> twins:=(x,n)->(igcd(x,n),n/igcd(x,n)):
> divs:=n->map(twins,f$2..isqrt(n)g,n) union f1,ng: p
The number of calls to igcd is now approximately equal to 2 n. This
means that in the case n = 40000, the last version of divs is 100 times faster
than the rst one! However, the function twins still makes two identical
calls to igcd; to x this problem, a more general form of procedures is
required (see chapter 9).
Exercises
Exercise 4.1. Consider the sequence n 7! fn = n=(n + 1).
(a) Construct a function f(n) whose value is fn.
(b) Plot the elements f0 ; : : : ; f30 , connecting points with segments.
(c) Using the function f, generate the rst 10 elements of the following
sequences
2 4 6 8 2 9 16 23
(i) 0; ; ; ; ; : : : (ii) ; ; ; ; :::
3 5 7 9 3 10 17 24

1 32 52 72 3 8 24 35
(iii) ; ; ; ; ::: (iv) 0; ; ; ; ; : : :
22 42 62 82 4 9 25 36
Exercise 4.2.
(a) Let n be a positive integer. Construct a function S(n) whose value is
the set of all rationals between 0 and 1 having the nth prime as denominator
(0 and 1 do not belong to S(n)).
(b) Let n be a positive integer, and let S (n) be the set of rationals between
0 and 1 having denominator n. Construct a user-de ned function for S .
(c) Verify that S (12) \ S (21) = S (3).
(d) From numerical experiments, conjecture the value of S (m) \ S (n), for
m; n  1.
Exercise 4.3. Construct the set of squares less than 5000 which are not
cubes, whence determine its cardinality.
Exercise 4.4 .
 Let m and n be integers with m  n, and let [m; n] be
an interval which includes the endpoints.
64 CHAPTER 4. SEQUENCES

(a) Construct a function findp(m,n) whose value is 1 if there is a prime


in [m; n], and 0 otherwise.
(b) Construct a function nprimes(m,n) whose value is the number of
primes in [m; n].

4.3 Plotting the elements of a sequence


Exploring the behaviour of a sequence graphically is standard practice in
experimental mathematics. In this section, we introduce the basic tools of
Maple's substantial graphics capabilities, and we apply them to the visual-
ization of sequences.
Maple's graphics are based on the all-purpose function plot, which can
plot | among other things | a discrete set of points on the plane
(x1 ; y1 ); (x2 ; y2); : : : ; (xn ; yn ):
A point (x; y) on the Cartesian plane is represented as a list of two ele-
ments. This is a new composite data type, consisting of a sequence en-
closed in square brackets: [x; y]. The set of points to be plotted must also
be organized in the form of a list, to give
[ [x1 ; y1 ]; [x2 ; y2 ]; : : : ; [xn ; yn ] ]:
The following commands generate a square, with vertices at the points
( 1; 1); (1; 0); (0; 2); ( 2; 1).
> sq:=[[-1,-1],[1,0],[0,2],[-2,1],[-1,-1]]:
> plot(sq);
2

1.5

0.5

-2 -1.5 -1 -0.5 0 0.5 1

-0.5

-1
4.3. PLOTTING THE ELEMENTS OF A SEQUENCE 65

> whattype(sq);
list
Maple automatically connects points with a segment, so the vertex ( 1; 1)
has to be entered twice, or one of the sides would be missing.
Plotting a sequence amounts to plotting points on the plane. Indeed, if
a1 ; a2 ; : : : ; an are elements of a sequence, they are represented by the points
(1; a1 ); (2; a2); : : : ; (n; an )
expressed in Cartesian coordinates. For illustration, let us consider the
graphical representation of the sequence of gaps between consecutive primes.
If pn is the nth prime we let
n 7! gn gn = pn+1 pn ; n = 1; 2; : : : :
We rst de ne a function for the sequence g
> g:=n->ithprime(n+1)-ithprime(n):
Then we construct the data set corresponding to the rst 300 elements of
this sequence, assign its value to a variable, and plot it
> gap:=[seq([n,g(n)], n=1..300)]:
> plot(gap,style=POINT,title="Gaps between primes");

Gaps between primes

30

25

20

15

10

0 50 100 150 200 250 300

The option style=POINT plots disconnected points. (Maple's default set-


ting | connecting point with segments | is style=LINE). A title has
66 CHAPTER 4. SEQUENCES

been inserted using the title option, which is set equal to an expression
enclosed within double quotes (a string data type). The gaps are even in-
tegers, except for the rst one: g1 = 3 2 = 1. An n increases, larger
gaps appear. Overall, the average gap size seems to increase, but in a very
irregular fashion (the study of this phenomenon was a major concern for
19th-century number theorists). The largest gap among the plotted data is
located approximately between the 200th and the 250th prime. To locate
it precisely, we magnify a portion of the graph, reverting to line style for
better visualization.
> plot(gap,n=200..250,"g(n)"=15..35);

35

30

g(n) 25

20

15 200 210 220 230 240 250


n

It is clear that the maximum of g occurs for n = 217, where the gap size is
34
> ithprime(217),ithprime(218);

1327; 1361

The second and third arguments of the call to plot de ne the ranges in the
horizontal and vertical axes, respectively, labelling the corresponding axes.
The labels must be strings, whence the expression g(n) has to be enclosed
within double quotes, for it contains parentheses. Any other option (such
as a title) must be placed after the range speci cations (see ?plot and
?plot[options] for more information).
4.4. PERIODIC AND EVENTUALLY PERIODIC SEQUENCES 67

4.4 Periodic and eventually periodic sequences


A sequence is periodic if it consists of inde nite repetition of the same nite
pattern
a0 ; a1 ; : : : ; aT 1 ; a0 ; a1 ; : : : ; aT 1 ; a0 ; a1 ; : : : ; aT 1 ; : : :
| {z } | {z } | {z }

The number of elements in the repeating block (T in this case) is called the
period of the sequence. Periodic sequences are of great interest.
A periodic sequence is speci ed by specifying its repeating block. Let the
period be equal to T , and the repeating block a0 ; a1 ; : : : ; aT 1 . Periodicity
is expressed concisely by the recursive notation
ak+T = ak k0 (4.5)
which says that an arbitrary element of the sequence is equal to the cor-
responding element in the previous block. Let this element be an . By
moving backwards from block to block, we eventually reach the rst block
a0 ; : : : ; aT 1 , so we can identify an with one of its elements an , where n0 0

is an integer lying between 0 and T 1. To compute n0 as a function of n,


we write n = qT + r, where q and r are the quotient and the remainder,
respectively, of the division of n by T . Then an belongs to the (q + 1)th
block, and occupies the rth place within the block (starting from r = 0).
Therefore, n0 = r, whence an = ar .
Example 4.7. Let

a:N ! f 1; 1g a := n 7! ( 1)n :
This sequence is periodic with period 2:
1| ;{z 1}; 1| ;{z 1}; 1| ;{z 1}; : : :

with the 2-element pattern 1; 1 repeating inde nitely. This sequence is


de ned recursively as follows (think about it)
a0 = 1 a1 = 1 an+2 = an ; n  0:
We modify the above sequence into a periodic binary sequence, assuming
the values 0 and 1, as follows
1 + an 1 + ( 1)n
b : N ! f0; 1g b := n 7! = :
2 2
Now the repeating block is 1; 0. Note that this is a representation of the
characteristic function of the odd integers.
Example 4.8. Fix a positive integer a. We consider the sequence

: n 7! gcd(n; a) n  0:
68 CHAPTER 4. SEQUENCES

We begin with an experiment, with a = 84.


> plot([seq([n,igcd(n,84)],n=0..200)]);

80

60

40

20

0 50 100 150 200

The sequence appears to be periodic with period a = 84. Moreover, each


repeating block appears to be symmetrical with respect to the midpoint.
We now show that this is indeed the case for every value of a. First of all,
the sequence is periodic with period a, that is, n = n+a for every n  0.
Indeed, let n = d. Then n = dq and a = dq0 , so that n + a = d(q + q0 ). This
shows that n + a is also divisible by d. If n + a and a had a common divisor
d0 greater than d, then d0 would also divide their di erence n + a a = n,
contrary to the hypothesis that d was the greatest common divisor of n
and a. Thus, d = gcd(n + a; a) = n+a . To prove the symmetry property
we must establish that gcd(n; a) = gcd(n; n a). The proof of the latter
statement is virtually identical to that given above, and will be left as an
exercise.
Example 4.9. Let : n 7! gcd(n; 5). Then is periodic with period 5.
Thus, 123456789 = 4 = 1.
A sequence is eventually periodic if it becomes periodic from a certain
point onwards:
b0 ; b1 ; : : : ; bS 1 ; a0 ; a1 ; : : : ; aT 1 ; a0 ; a1 ; : : : ; aT 1 ; a0 ; a1 ; : : : ; aT 1 ; : : :
| {z } | {z } | {z } | {z }

An eventually periodic sequence has an initial non-repeating part. The


number of its elements is called the transient length. The condition (4.5)
now becomes
ak+T = ak k  S:
4.4. PERIODIC AND EVENTUALLY PERIODIC SEQUENCES 69

Example 4.10. Consider the sequence de ned by the characteristic func-


tion of the subset f0g of N ; see (3.16). This sequence is eventually periodic
with period 1 and transient length 1.
> chi:=n->if n = 0 then 1 else 0 fi:
> seq(chi(i),i=0..5);
1; 0; 0; 0; 0; 0
The quotient and remainder of integer division are functions of two
integer variables. By xing one variable and letting the other run through
the integers, we obtain eventually periodic sequences of great interest.
We begin by considering the quotient and the remainder of the division
of a xed integer n by d
d 7! quo(n; d) d 7! rem(n; d); d = 1; 2; : : : (n xed):
Below, we tabulate the rst few elements of these sequences, in the case
n = 5.
d 1 2 3 4 5 6 7 8 9 10 11 12
quo(5; d) 5 2 1 1 1 0 0 0 0 0 0 0
rem(5; d) 0 1 2 1 0 5 5 5 5 5 5 5
Both sequences become eventually periodic with period 1, after a transient
for 1  d  5. To prove this for an arbitrary value of n, we consider
equation (2.10) in the range d > n
n=d0+n n < d: (4.6)
This shows that in the above range the sequence d 7! quo(n; d) is identically
zero. For d  n such sequence displays a transient behaviour, decreasing
from n (at d = 1) to 1 (at d = n).
From (4.6) it also follows that the sequence d 7! rem(n; d) is identically
equal to n for d > n. The transient behaviour in the range 1  d  n is more
complicated, although it still displays a considerable degree of regularity,
as illustrated by the gure on the following page, for the case n = 200.
70 CHAPTER 4. SEQUENCES

> plot([seq([d,irem(200,d)],d=1..300)]);

200

150

100

50

0 50 100 150 200 250 300

The sequence assumes the value 0 in correspondence to all divisors of n,


and its value is small whenever d = quo(n; k), for k = 1; 2; : : : ; n.

4.5 Some non-periodic sequences


Periodic or eventually periodic sequences are, in a sense, atypical. We
consider some instances of departure from this behaviour, to gain familiarity
with some common patterns.
A simple but important case is that of linear rational sequences
L:N !Q n 7! a  n a 2 Q: (4.7)
If a 6= 0, then Ln diverges to +1 or 1 depending on the sign of a.
Adding a (eventually) periodic sequence to a linear one yields interesting
behaviour. These sequences take the form
n 7! L(n) + P (n) (4.8)
where P is a (eventually) periodic function. In the special case when P is
a constant function, the sequence is said to be aÆne.
For illustration, we consider the quotient and the remainder of the di-
vision of n by a xed integer d
n 7! quo(n; d) n 7! rem(n; d); n = 0; 1; : : : ; (d xed):
Below we tabulate the rst few elements of these sequences, in the case
d = 5.
4.5. SOME NON-PERIODIC SEQUENCES 71

n 0 1 2 3 4 5 6 7 8 9 10 11 12
quo(n; 5) 0 0 0 0 0 1 1 1 1 1 2 2 2
rem(n; 5) 0 1 2 3 4 0 1 2 3 4 0 1 2
The rst sequence displays a step-like behaviour, with steps of length 5 and
height 1. The second is periodic with period 5; i.e., it consists of inde nite
repetition of the same 5-pattern 0; 1; 2; 3; 4. This behaviour persists when
one replaces 5 by an arbitrary value of d. To prove it, we consider the
quotient-remainder equation (2.10). Replacing n by n + d we obtain
n + d = d (q + 1) + r 0  r < d; (4.9)
which shows that the quotient increases by 1 every d steps. Because the
quotient cannot decrease when n increases, then it must increase by 1 pre-
cisely once every d steps. Thus, the sequence n 7! quo(n; d) has a step-like
behaviour, increasing by 1 when n is a multiple of d.
Equations (2.10) and (4.9) show that dividing n and n + d by d gives the
same remainder. So the sequence n 7! rem(n; d) is periodic, with period at
most d. To show that the period is exactly d, we note that as n increases
by 1, then r either increases by 1 (if r 6= d 1), or it becomes zero (if
r = d 1).
The step-like behaviour of n 7! quo(n; d) can be thought of as the result
of superimposing a linear and a periodic sequence. From equation (2.10)
we obtain
1 r(n)
q(n) = n
d d
where the n-dependence of q and r has been made explicit. This sequence
has the form (4.8), with a = 1=d and P (n) = r(n)=d. The sequence P is
periodic with period d, because r is periodic with the same period.
Next we consider the modulation of a linear sequence by a periodic one.
With reference to (4.7) we have n 7! a(n)  n, where the function a = a(n)
is periodic. As an example, consider the sequence
 : n 7! lcm(n; d) (d 6= 0 xed):
Because d  lcm(n; d)  nd, we obtain
n  n  nd: (4.10)
From (2.28) and the fact that gcd(n; d) 6= 0, we have
d
lcm(n; d) = n  :
gcd(n; d)
Because of the periodicity of the greatest common divisor, we see that
n 7! lcm(n; d) is the product of a linear and a periodic function.
72 CHAPTER 4. SEQUENCES

We wish to plot n , showing graphically the bounds (4.10), for d = 10


and 1  n  N . Because the bounding sequences n 7! n (lower bound)
and n 7! d  n (upper bound) are just straight lines, we plot them directly
as two solid line segments. The parameters of the problem (the values of d
and N ) are stored into variables, to gain in generality.
> N:=100:
> d:=10:
> lower:=[[1,1],[N,N]]:
> upper:=[[1,d],[N,N*d]]:
Next we construct the data set for the sequence n
> data:=[seq([n,ilcm(n,d)],n=1..N)]:
The three data sets lower, upper, and data must be arranged in a list
(which is now a list of lists of lists!). The rst two are to be represented as
solid lines, and the third as a dotted line, as follows
> plot([lower,upper,data], linestyle=[1,1,2]);

1000

800

600

400

200

0 20 40 60 80 100

The option linestyle is equated to a list of integers containing as many


elements as the number of data sets to be plotted. The values 1 and 2
correspond to a solid and a dotted line, respectively. The reader is invited
to explore the various e ects that can be obtained by changing the value
of linestyle.
Up to now, we have considered non-repeating sequences ranging in an
in nite set. But even in a nite set, e.g., f0; 1g, it is easy to construct
4.5. SOME NON-PERIODIC SEQUENCES 73

ordered patterns that never repeat, such as


1; 0; 0; 1; 1; 1; 0; 0; 0; 0; 1; 1; 1; 1; 1; 0; 0; 0; 0; 0; 0; 1; 1; 1; 1; 1; 1; 1; 0; : : :
Equally interesting are non-repeating sequences which display no regularity
at all, the random sequences. A random sequence seems a contradiction in
terms. How can it be random if it can be de ned? This is a delicate and
interesting problem, which we shall brie y address in the next chapter in
connection with random sequences of digits. Here we merely note that nd-
ing random-like behaviour in arithmetic is not at all diÆcult. For instance,
a seemingly inexhaustible source of irregular and unpredictable phenomena
can be found in the sequence of primes, as the following example illustrates.
Example 4.11. Let pn be the nth prime. For n > 2, the remainder of the
division of pn by 3 is equal to 1 or 2 (it cannot be equal to zero; otherwise,
pn would be divisible by 3). Consider the following binary sequence
 : n 7! rem(pn ; 3) 1 n  3:
This sequence displays a great deal of irregularity:
> theta:=n->irem(ithprime(n),3)-1:
> seq(theta(n),n=3..30);

1; 0; 1; 0; 1; 0; 1; 1; 0; 0; 1; 0; 1; 1; 1; 0; 0; 1; 0; 0; 1; 1; 0; 1; 0; 1; 0; 1

Farey sequences 
For every integer n  1, let Fn be the set of rational numbers in the unit
interval, whose denominator does not exceed n
 
p
Fn =
q
2 Q; 1  q  n; 0  p  q : (4.11)

Thus,  
0 1
F1 = ;
1 1 
0 1 1
F2 = ; ;
1 2 1 
0 1 1 2 1
F3 = ; ; ; ;
1 3 2 3 1 
0 1 1 1 2 3 1
F4 = ; ; ; ; ; ;
1 4 3 2 3 4 1 
0 1 1 1 2 1 3 2 3 4 1
F5 = ; ; ; ; ; ;
1 5 4 3 5 2
; ; ; ;
5 3 4 5 1
:
We have a nested sequence of nite sets, each properly contained in the
following one:
F1  F2  F3  : : : :
74 CHAPTER 4. SEQUENCES

The set Fn is called the nth Farey sequence (the appellative `sequence'
derives from the fact that the elements of the set Fn are usually considered
in ascending order). For each n and each denominator q in the range
1  q  n, the corresponding numerator ranges from 0 to q, inclusive. In
this way, some fractions appear several times, but multiple occurrences are
eliminated in accordance with the de nition of a set. For instance, 0 = 0=q
and 1 = q=q appear for every value of q, while 1=2 appears only when q is
even.
We wish to construct a user-de ned function F(n) whose value is the
set Fn . We shall not be concerned with the ordering of the elements of Fn
(from the smallest to the largest), and accordingly we shall be using the set
data type. This will enable us to eliminate repeated entries automatically.
The starting point is to construct an expression sequence containing all
fractions with a given denominator q. (We exclude the elements 0 and 1,
to limit the number of repeated entries.)
> seq(p/q,p=1..q-1):
Next we embed the above sequence within an expression sequence which
determines the range of values assumed by the denominator q.
> seq(seq(p/q,p=1..q-1),q=2..n):
Then we add the missing elements 0 and 1, and construct the corresponding
set data type.
> f0,1, seq(seq(p/q,p=1..q-1),q=2..n)g:
Finally, we construct a user-de ned function whose value is the above ex-
pression.
> F:=n->f0,1, seq(seq(k/d,k=1..d-1),d=2..n)g:
> F(5);
 
1 1 2 1 3 1 2 3 4
0; 1; ; ; ; ; ; ; ; ;
2 3 3 4 4 5 5 5 5

Exercises
Exercise 4.5. Consider the following sequences n 7! an (pn denotes the
nth prime number)

(1) n 7! n2 + 100 n0


(2) n 7! lcm(n; 6) 6n n1
(3) n 7! gcd(n; 2) gcd(n; 3) n1
(4) n 7! pn+1 (pn + 1) n2
(5) n 7! quotient of division of 3n by 7 n0
(6) n 7! remainder of division of pn by 8 n1
4.5. SOME NON-PERIODIC SEQUENCES 75

2
(7) n 7! true if n + 1 is prime n0

false otherwise
2
(8) n 7! true if n > 7n 7 n0
n
false otherwise
(9) n 7! 0 if (an + 1)=2 is even (an as in part 6) n2
n 1 otherwise
(10) n 7! 1 if n is relatively prime to 12 n  1:
0 otherwise
 For each sequence an , construct a user-de ned function a(n). Test it
for small values of n.
 Display/plot the rst few terms, and then display/plot a few terms
after the 1000th one.
 From the result of your experiment, formulate a conjecture on the
behaviour of the sequence for large n. Try to provide a supporting
argument.
Exercise 4.6. The following tongue twister is an exercise in logic. We
de ne
M = 104 an = n2 + n + 17; n  0:
(a) Determine the smallest value of n for which an is not prime.
(b) Determine the smallest value of n for which an is prime and greater
than M .
(c) Determine the smallest prime value of n for which an is greater than
M.
(d) Determine the smallest value of n greater than M for which an is prime.
(e) Determine the largest prime value of n smaller than 2M for which an
is prime.
Exercise 4.7. Consider the following binary sequence
n
k = 0 if k is divisible by a square k > 1:
1 otherwise
For instance, (24) = 0, since 24 = 23  3 is divisible by the square 22 . On
the other hand, (26) = 1, since 26 = 2  13 has no square divisor.
(a) By considering the prime factorization of k, compute k for k =
1000; : : : ; 1005. (Alternatively, you may wish to explore the Maple library
numtheory).
(b) Compute the rst 5 terms of the sequence
n = n ; n = 1; 2; : : :
where  is as in part (a) and
n = 3n + 5 n; n = 1; 2; : : :
(Consider the de nition of n carefully.)
76 CHAPTER 4. SEQUENCES

Exercise 4.8. Plot the elements of the sequence d 7! rem(n; d) for n =


100, and 1  d  100. Show that for d > n=2, the value of this sequence is
n d.
Exercise 4.9. Let p be an odd prime. Use the periodicity of the sequence
n 7! rem(n; 3) to show that p + 2 and p + 4 cannot both be prime.
Exercise 4.10. Let us consider the following sequence
8 1
f : N+ ! Q n 7! 3 :
8+n 3
(a) By examining the plot of f (x) for x in the range 0  x  10, con-
vince yourself that this sequence contains only a nite number of positive
elements, and identify them. More precisely, determine an integer k such
that
rk > 0 rk+t < 0; t = 1; 2; 3; : : : (4.12)
(b) Prove the above statement, with Maple's help. First show that, for the
value of k of equation (4.12), rk > 0 and rk+1 < 0, by direct computation.
Then compute the derivative of f using the operator diff ( nd out about
it with the online help system), and verify that it is negative for all x > 0.
Why is this enough? (You may call this a computer-assisted proof, albeit a
very simple one.)
Exercise 4.11. Let n be a natural number, and let rn be the remainder
of the division of 2n by 23.
(a) Compute r0 ; : : : ; r6 by hand.
(b) Compute rn with Maple for a suÆcient number of small values of n,
until you can guess what is the behaviour of the sequence. Describe your
ndings in the form of a conjecture.
(c) Assuming the validity of your conjecture, compute r123456789 (you can't
compute it directly, yet!).
Exercise 4.12. We consider the prime decomposition of n > 1 given by
(2.25). We assume that the primes pi are all distinct and form an increasing
sequence, that is
pi < pi+1 i = 1; 2; : : : ; k 1:
For each n, there are well-de ned integers Rn = k (the number of prime
divisors of n), Pn = pk (the largest prime divisor of n), and En = ek (its
exponent). (Make sure you understand the meaning of pk and of ek , and
why the primes in equation (2.25) must be distinct and in ascending order
for k, pk , and ek to be de ned unambiguously. Also note that there is no
explicit formula expressing Rn , Pn , and En as a function of n.)
Compute and tabulate the values of Rn , Pn , and En for n equal to the
rst 5 elements of the sequence
n = n(l) = 5l 4l 1 l = 1; 2; : : :
4.6. BASIC COUNTING SEQUENCES 77

(Note: Maple does not always display the prime divisors of an integer in
ascending order.)
Exercise 4.13. Let rn be the remainder of the division of the nth prime
number by 12 (thus, r6 = 1). It can be shown that for n  3, rn assumes
only the four values 1; 5; 7; 11 (can you prove it?). Write a user-de ned
function K(n) for the following characteristic function

K (n) = 1 if rn = 1 or 11
1 if rn = 5 or 7.
Exercise 4.14. Let Pk be the set of primes not greater than k, and let
Fk : Pk ! Z be the function sending x to x (x k). Construct Pk and
hence compute jFk (Pk )j, for k = 2309 and 2310. For which of these values
of k is Fk injective?

4.6 Basic counting sequences


Some important sequences originate from the process of counting elements
of certain sets, such as the number of permutations of a set of n objects, or
the number of combinations of n objects, taken k at a time. The process
of counting is the main concern of a branch of discrete mathematics called
combinatorics.
The factorial function and permutations
An important function built from multiplication is the factorial function.
If n is a positive integer, the factorial of n, denoted by n!, is de ned as the
product of all positive integers up to and including n, namely
n
Y
n! = 1  2  3    (n 1)  n = k; n  1:
k=1

Thus, 5! = 1  2  3  4  5 = 120. From this de nition it follows that


(n+1)! = 123    n(n+1) = (123    n)(n+1) = (n+1) n! n  1:
This gives a recursive de nition of the factorial function | the de nition
of a function in terms of itself
1! = 1; (n + 1)! = (n + 1) n! n  1: (4.13)
Equation (4.13) is valid only for positive n. We disregard this, and set
n = 0, which gives
1! = 0!  1 =) 0! = 1:
So we have de ned the factorial function for all elements of N
0! = 1; (n + 1)! = (n + 1) n! n  0: (4.14)
78 CHAPTER 4. SEQUENCES

This result could not have been extracted from the de nition (4.13), because
for n = 0 the product is empty. With this device, we have extended the
de nition of the factorial function to all non-negative integers. Note that
this procedure cannot be used to extend the de nition of the factorial to
negative integers | try!
Factorials grow very rapidly. Below we compare the factorial function
with the exponential functions 2n ; 3n, and 4n , for n < 10.
n 0 1 2 3 4 5 6 7 8 9
n! 1 1 2 6 24 120 720 5040 40320 362880
2n 1 2 4 8 16 32 64 128 256 512
3n 1 3 9 27 81 243 729 2187 6561 19683
4n 1 4 16 64 256 1024 4096 16384 65536 242144
For any b > 1 the function bn is initially greater than n!, but the factorial
function eventually takes over. For instance, when b = 100 one nds that
n! overtakes 100n at n = 269.
What is the combinatorial meaning of the factorial function? We de ne
the concept of a permutation. A permutation of n objects in a row is a
rearrangement of them. The following is a permutation of n = 6 objects,
called a; b; c; d; e; f
a b c d e f 7! d a b f e c
(Formally, this is just a bijection of the set fa; b; c; d; e; f g.) How many
possible permutations of n objects are there? Let us call this number n .
Clearly 1 = 1 and 2 = 2. For n = 3 we have
abc acb bac bca cab cba:
Thus, 3 = 6. With a little patience, one nds that 4 = 24 and the
temptation to conjecture n = n! is irresistible.
This is indeed the case and the proof is simple. There are n ways of
choosing the position of the rst object. For every choice of the rst object
there are n 1 ways to choose the position of the second, so we have n(n 1)
choices of the destination of two objects, and so forth, until we reach the
last object for which there is only one choice, because the remaining n 1
objects are already in place.
It is possible to extend the de nition of the factorial function to real
numbers. The resulting function | called the gamma function | will be
dealt with in section 5.5.
The binomial coeÆcient and combinations n
Let n and k be positive integers. The binomial coeÆcient k is de ned as
follows  
n n (n 1) (n 2)    (n k + 1)
= : (4.15)
k k!
4.6. BASIC COUNTING SEQUENCES 79

Thus,  
6 654
= = 20:
3 123
One nds immediately from the de nition
   
n n n(n 1)
=n = :
1 2 2
If k = 0 in (4.15), the product at the numerator is empty. In this case, we
de ne  
n
= 1:
0
We look at small values of n and k, by displaying Pascal's triangle
1
1; 1
1; 2; 1
1; 3; 3; 1
1; 4; 6; 4; 1 (4.16)
1; 5; 10; 10; 5; 1
1; 6; 15; 20; 15; 6; 1
1; 7; 21; 35; 35; 21; 7; 1
1; 8; 28; 56; 70; 56; 28; 8; 1
The rows are labelled by the value of n, starting from 0 and proceeding from
top to bottom. The elements of the nth row are labelled by k, starting
 from
k = 0 and proceeding from left to right up to k = n. For example, 75 = 21.
We note that the binomial coeÆcient is an integer, which is not at all
obvious from de nition (4.15). To prove this, we turn to the combinatorial
interpretation of the binomial coeÆcient. A combination of n objects taken
k at a time is any subset of k objects from a set of n distinct objects
(this is where the word combinatorics comes from!). The order in which
these objects are arranged makes no di erence. For instance, there are
10 combinations of ve objects taken two at a time, that is, 10 ways of
selecting two objects out of a set of ve. If the ve objects are taken from
the set fa; b; c; d; eg, then the 10 subsets of 2 elements are
fa; bg; fa; cg; fa; dg; fa; eg; fb; cg; fb; dg; fb; eg; fc; dg; fc; eg; fd; eg:
The number of combinations  of n objects taken k at a time is given
by the binomial coeÆcient nk . To see this, we rst select k elements and
arrange them in a sequence (that is, in a speci ed order). There are n
choices for the rst element of the sequence. For each such choice there are
n 1 choices for the second element, and so forth, until we choose the kth
element, which can be done in n k + 1 di erent ways. In all, we obtain
n(n 1)    (n k +1) sequences with k elements. But since in a combination
80 CHAPTER 4. SEQUENCES

the order in which these elements are arranged is irrelevant, we must divide
this number by all possible permutations of k objects, which we found to
be equal to k!. So the number of combinations is n(n 1)    (n k + 1)=k!,
which is the binomial coeÆcient (see (4.15)).
The binomial coeÆcient can be represented in terms of factorials as
follows
 
n n (n 1) (n 2)    (n k + 1)
=
k k!
n (n 1) (n 2)    (n k + 1) (n k)!
=
k! (n k)!
n!
= :
k! (n k)!
From this we obtain    
n n
= : (4.17)
k n k
If n < k, then n k + 1 is either 0 or negative. Then, from (4.15)
 
n n (n 1)    1  0  1    (n k + 1)
= = 0:
k k!
Taking into account (4.17), we see that for xed n, the binomial coeÆcient
can be de ned for any integer k, positive or negative, but its value will be
nonzero only for 0  k  n. 
The binomial coeÆcient nk is implemented in Maple by the function
binomial(n,k)
> evalb(binomial(10,4)=10!/(4!*(10-4)!));
true
To save typing, we can shorten the symbolic name binomial to bc via the
alias statement as follows
> alias(bc=binomial):
This will cause Maple to translate bc(n,k) into binomial(n,k).
> seq(bc(8,k),k=-2..10);
0; 0; 1; 8; 28; 56; 70; 56; 28; 8; 1; 0; 0
The name binomial coeÆcient derives from the following result, called
the binomial theorem
Theorem 2

n  
X n k n
(x + y) =
n
xy k
n  0:
k=0
k
4.6. BASIC COUNTING SEQUENCES 81

To see the binomial theorem in action, we expand the expression (x + y)8


(cf. (4.16))
> expand((x+y)^8);

x8 + 8 x7 y + 28 x6 y2 + 56 x5 y3 + 70 x4 y4 + 56 x3 y5 + 28 x2 y6 + 8 xy7 + y8
Setting x = y = 1 and x = 1; y = 1 in Theorem (2), respectively, we
obtain the well-known identities
n   n  
X n X n
= 2n ( 1)k
= 0:
k=0
k k=0
k

Exercises
Exercise 4.15.

(a) Determine how many di erent football teams (11 players) can be made
out of 30 players.
(b) De ne a function row(n) whose value is the nth row of Pascal's triangle,
in the form of an expression sequence. Thus,
> row(3);
1; 3; 3; 1
(c) Using row generate the rows from 0 to 7 of Pascal's triangle.
(d) In Pascal's triangle, observe the symmetry induced by the identity
   
n n
=
k n k
which causes every entry to appear exactly twice, except when n is even,
in which case there is a unique central element. Construct the sequence of
the central elements of the even rows of Pascal's triangle
 
2m
cm = m  0:
m
Compute c15 ; c50 .
(e) Find an explicit formula for cm , involving factorials. Check your for-
mula with Maple, in the case m = 200.
(f ) Plot the coeÆcients of (1 + x)30 . Convince yourself that the value of
the central coeÆcient as inferred from the plot is consistent with what you
have computed in part (d).
(g) From the plot alone, determine how many coeÆcients are larger than
108 , identifying explicitly the indices of the corresponding binomial coef-
cients. Then compute all the coeÆcients that are greater than 108 with
Maple.
82 CHAPTER 4. SEQUENCES

Exercise 4.16. The following identity holds


n            
X s k k+1 n 1 n n+1
= + +  + + = : (4.18)
s=k
k k k k k k+1
(a) Verify equation (4.18) by hand, in the cases k = 0; n = 2 and
k = 1; n = 2.
(b) Verify equation (4.18) in the cases k = 9; n = 13 and k = 1000,
n = 1002.

4.7 Sequences de ned recursively


In this chapter, we have dealt mainly with sequences given by explicit func-
tions of the integers
xt = an explicit function of t t  1:
We have pointed out that this construction is not always possible. However,
how can one characterize the structure of a sequence whose terms cannot
be de ned explicitly? A very interesting special case is that of sequences
de ned recursively, which in the simplest instance have the structure
xt = an explicit function of xt 1 t  1; (4.19)
that is, each element of the sequence is de ned as an explicit function of
the previous element. A sequence of this type, called a rst-order recursive
sequence, is uniquely de ned once we specify the rst element x0 , which is
called the initial condition.
Speci cally, let us consider a set A, an element 2 A, and a function
f : A ! A. The recursive sequence generated by f with initial condition
is de ned as follows
x0 = xt = f (xt 1 ); t  1:
The rst few terms of this sequence are
x0 = ; x1 = f (x0 ) = f ( ); x2 = f (x1 ) = f (f ( )); : : :
In a recursive sequence, the rule that associates to the integer t the element
xt is: \apply f to x0 t times".
Example 4.12. Let
f : Z! Z f := x 7! 2x + 1:
The corresponding recursive sequence with initial condition x0 = 1 is
given by
x0 = 1; x1 = f ( 1) = 3; x2 = f (3) = 5; x3 = f ( 5) = 11; : : :
4.7. SEQUENCES DEFINED RECURSIVELY 83

In Maple, there is no need for subscripts


> f:=z->-2*z+1:
> x:=-1;x:=f(x);x:=f(x);x:=f(x);
x := 1
x := 3
x := 5
x := 11
We can even dispose of variables altogether
> -1;f(%);f(%);f(%);
1
3
5
11
It should be clear that the sequence changes by changing initial conditions
> -2;f(%);f(%);f(%);
2
5
9
19
Example 4.13. Let 2 be the set of all words of the two letters a and
b (see (3.5)). Let w 2 2 . We de ne a function f : 2 ! 2 whose value
at w is the word whose letters are obtained from those of w by replacing
every a with b and every b with ab. Thus, if w = aaba then f (w) = bbabb.
Then we have the recursive sequence
w0 = w wt+1 = f (wt ); t  0:
For instance, the initial condition w0 = a gives
a; b; ab; bab; abbab; bababbab; : : : (4.20)
To implement the above construct in Maple, we represent a word as a list
of the symbols a and b
> w:=[a,b,b,b]:
Constructing the function f requires simultaneous substitutions, obtained
by enclosing the substitution list between curly brackets (see section 2.3)
> f:=w->subs(fa=b,b=(a,b)g, w):
(Persuade yourself that sequential substitutions would not work in this
case.) Note that the second argument in the substitution list required the
use of round brackets: without them the substitution list would be inter-
preted as a=b,b=a,b, resulting in an error termination when the function
is called. Thus,
84 CHAPTER 4. SEQUENCES

> f([a,b,b]);
[ b; a; b; a; b ]
The construction of the recursive sequence (4.20) now proceeds as usual,
e.g.,
> [a]:f(%):f(%):f(%):f(%):f(%);
[ b; a; b; a; b; b; a; b ]
In the general case, a sequence de ned recursively has the following
structure
xt = f (xt 1 ; xt 2 ; : : : ; xt s ; t) t  s: (4.21)
Here f is an arbitrary function of xt 1 ; xt 2 ; : : : ; xt s as well as of t. Such a
sequence is speci ed by assigning the s initial values x0 ; x1 ; : : : ; xs 1 . The
integer s is called the order of the recursion. If the function f in (4.21)
depends on t, the recursive sequence is said to be non-autonomous.
Example 4.14. The factorial sequence (4.14) is a rst-order non-autonom-
ous recursive sequence. With the notation of (4.21), we have f (xt 1 ; t) =
t  xt 1 .
Example 4.15. The Fibonacci numbers. We consider the recursive se-
quence
F0 = 1 F1 = 1 Ft+1 = Ft + Ft 1 ; t  1:
With reference to (4.21), we have f (xt 1 ; xt 2 ) = xt 1 + xt 2 , and there-
fore this is a second-order autonomous recursive sequence (s = 2 and no
dependence of f on t). The rst few elements of this sequence are displayed
below

t 0 1 2 3 4 5 6 7 8 9 10 11 12 
Ft 0 1 1 2 3 5 8 13 21 34 55 89 144 
The numbers Ft are known as Fibonacci numbers (named after the 13th-
century mathematician Leonardo da Pisa, nicknamed Fibonacci). They
have several important combinatorial applications. We compute F10 with
Maple
> 0:1:%+%%:%+%%:%+%%:%+%%:%+%%:%+%%:%+%%:%+%%:%+%%;
55
Maple has a library function generating the Fibonacci numbers. For details,
see ?fibonacci.
Example 4.16. We prove by induction the following identity (discovered
by Cassini in 1680)
Fn+1 Fn 1 F 2 = ( 1)n
n n  1: (4.22)
4.7. SEQUENCES DEFINED RECURSIVELY 85

Equation (4.22) is true for n = 1. Assume it true for an arbitrary n  1.


Then
Fn+2 Fn Fn2+1 = (Fn+1 + Fn )Fn Fn+1 (Fn + Fn 1)
= Fn+1 Fn + Fn2 Fn+1 Fn Fn+1 Fn 1
= ( 1)n = ( 1)n+1 :
This shows that (4.22) is valid for all positive integers n.
Exercises
Exercise 4.17. The factorial sequence n! was de ned recursively in (4.14).
We de ne the analogous rst-order non-autonomous recursive sequence n?
as follows
 
1
0? = 1 (n + 1)? = n +
2
 n? n  0:
Compute 6?.
Exercise 4.18. Consider the following second-order autonomous sequence
| cf. (4.21)
f0 = 0 f1 = 1 fn+1 = 11  fn + fn 1; n  1:
(Note that this sequence is determined by two initial conditions, f0 and
f1 .) Show that f6 and f7 are relatively prime.
Exercise 4.19. Let r be a rational number, and let f be given by
3 2 5
f :Q !Q f := x 7!
2
x + x + 1:
2
We consider the rst-order recursive sequence of rational numbers
r0 = r rt+1 = f (rt ); t  0: (4.23)
(a) Show that if rt is an integer, so is rt+1 . [Hint: consider the cases rt
even and odd separately.]
(b) Let r0 = 4. Show that r4 is divisible by 857, hence determine the
smallest value of t for which rt < 1040.
(c) Let r0 = 4=3. Show that for t  2 the sequence repeats inde nitely,
and compute its period (the length of the repeating part). Hence compute
r1000 .
Exercise 4.20. Consider the recursive sequence (4.23), with f given by

3x + 1
f :Q !Q f := x 7!
x+3
:
86 CHAPTER 4. SEQUENCES

(a) Construct the Boolean characteristic function  of the set of rationals


whose distance from 1 is less than 1/100.
(b) Consider the sequence corresponding to the initial condition r0 = 1=2.
Convince yourself that rt approaches the point x = 1. Hence, using the
function , determine the smallest value of t for which the distance between
rt and 1 is smaller than 1/100.
(c) Prove that if r0 = 1, then rt = 1 for all positive t.
(d) Construct the function fp(r) whose value is the fractional part of r.
(e) Let Q I denote the set of rational numbers lying between 0 and 1. Thus,
Q I consists of all rationals r = m=n with 0 < m < n. Consider the function
 
1
g : QI ! Q I [ f0g g := r 7!
r
: (4.24)

Prove that g is indeed a function of Q I into Q I [ f0g; that is, prove that if
r 2 Q I , then g(r) 2 Q I [ f0g.
(f ) Using the function fp developed above, construct the function g(r)
given by (4.24).
(g) Consider the following recursive sequence

g(rt ) rt 6= 0
r0 = r rt+1 = t  0: (4.25)
0 otherwise
Let r = 11=19. Determine the smallest value of t for which rt is equal to
zero.
(h) Choose an arbitrary rational number r 2 Q I . Verify that the corre-
sponding sequence rt eventually reaches zero.
(i) Prove that for any choice of r 2 Q I , the sequence rt with initial condi-
tion r0 = r reaches 0 in a nite number of steps.
Exercise 4.21 .
 Let the sequence rt be as in (4.25). From the previous
problem it follows that to every rational r in QI we can associate the natural
number  (r), which is the number of iterations needed to reach zero starting
from r
 : QI !N  := r 7! smallest t for which rt = 0, and r0 = r:
For instance,  (4=7) = 3, because
4
r0 =
7
! r1 = g(r0 ) = 34 ! r2 = g(r1 ) = 13 ! r3 = g(r2 ) = 0:
(4.26)
Now let Fn be the nth Farey sequence, de ned in (4.11). Then Fn is a
nite subset of Q I . Let n be the maximum value attained by  (r) as r
scans all the elements of the set Fn . For example, since 3=4 2 F5 , from the
data (4.26) we obtain the estimate 5  2 (in fact, 5 = 3).
4.7. SEQUENCES DEFINED RECURSIVELY 87

Find a good estimate for n , in the case n = 10000. Speci cally, obtain
an estimate 10000  by producing a rational r in F10000 for which =
 (r) is as large as possible. You must display the calculations showing that
the sequence with initial condition r reaches zero in steps. [Hint: The set
F10000 has 30397486 elements. Careful experimentation and thinking will
get you much further than blind trial and error.]
Exercise 4.22. In this problem, we compare the growth rate of the expo-
nential sequence 2n with that of the power sequence nb , where b is a given
integer greater than 1, and n = 1; 2; : : : . Both sequences diverge to in nity,
but the exponential `gets there rst'; that is, it grows faster than any power.
However, the sequence of powers starts o faster than the exponential (for
n > 1) but is eventually overtaken by the latter. This phenomenon |
illustrated below for the cases b = 2 and 3 | becomes more pronounced as
b gets large.
n 1 2 3 4 5 6 7 8 9 10
2n 2 4 8 16 32 64 128 256 512 1024
n2 1 4 9 16 25 36 49 64 81 100
n3 1 8 27 64 125 216 343 512 729 1000
Ignoring the value n = 1, we see that 2n overtakes n2 at n = 5, and n3 at
n = 10.
For xed b > 1, let Ob be the smallest n > 1 for which 2n > nb
Ob : n 7! smallest n for which 2n > nb n > 1; b  1:
Thus, Ob is the integer at which 2n overtakes nb , whence O2 = 5 and
O3 = 10, from the above data. Compute and tabulate Ob for b = 2; : : : ; 10.
Display only the calculations that suÆce to establish your result.
Exercise 4.23. In this problem, we compare the behaviour of the factorial
function n! with that of the exponential function bn , where b is a given
positive integer. Convince yourself that for any xed b  1, n! is smaller
than (or equal to) bn for suÆciently small n. However, the factorial function
is known to grow faster than any exponential, so at some point n! will
overtake bn .
Let Ob be the point at which the factorial overtakes the powers of b. So
we have an integer sequence O1 ; O2 ; O3 ; : : : . Compute and tabulate Ob for
b = 2; : : : ; 10. Display only the calculations that suÆce to establish your
result.
Exercise 4.24. Consider the following recursive sequence

0=1 k+1 = f ( k ) =
2 + 1; k  0:
k

(a) Show that 6 is divisible by 1277.


88 CHAPTER 4. SEQUENCES

(b) Show that 9 has 91 decimal digits, without using length. [Hint: how
do you show that 88 has two decimal digits?]
(c) This is the fastest-growing sequence you have come across so far. It
grows faster than the factorial sequence. Indeed, k eventually overtakes
(k!)b for any positive integer b. Let Ob be the point at which k overtakes
(k!)b . Compute O1 and O2 .
Exercise 4.25. Construct the fastest-growing sequence you can think
of. Speci cally, replace the 10 question marks in the following function
de nition
> fast:=n->??????????;
with at most 10 characters so as to obtain a Maple function fast(n),
representing a rapidly growing sequence de ned for all positive n. (Any
character that is on the keyboard is allowed, but you cannot make use of
functions you have de ned elsewhere.)
What counts is the asymptotic behaviour of your sequence (how fast it
grows when n becomes very large). For instance, n ! n2 starts slower than
n ! n + 1010 , but it gets to in nity rst.
Chapter 5

Real and complex


numbers
Every rational number is representable as a pair of integers, the numerator
and the denominator. Are all numbers rational? If not, can at least all
numbers be represented as a nite collection of integers? The answer to
both questions turns out to be no, but a satisfactory explanation is far from
simple. There are a lot more numbers than the rationals, and the numbers
that are representable as a nite collection of integers are still extremely
rare (but also extremely interesting). Yet, based on the limited evidence
we have gathered so far, it is hard to be convinced that almost all numbers
are not rational. For instance, if we represent the rationals as points on a
line, we can nd them as close as we please to any given point.
This chapter is devoted to answering our rst question. To do so we
must rst introduce a new way of representing numbers, the representation
in terms of decimal digits.

5.1 Digits of rationals

One of the best-known numbers is 

 = 3:141592 : : :
89
90 CHAPTER 5. REAL AND COMPLEX NUMBERS

This notation is shorthand for a sum


 = 3
+ 0:1
+ 0:04
+ 0:001
+ 0:0005
+ 0:00009
+ 0:000002
..
.
Each term in the sum is rational
1 4 1 5 9 2
 = 3  100 + 1 + 2 + 3 + 4 + 5 + 6 +  (5.1)
10 10 10 10 10 10
and one sees that the decimal point (or radix point ) separates the non-
negative powers of 10 from the negative ones. Can we conclude that  |
as a sum of rationals | is itself rational? Not necessarily.
We know that Q is closed with respect to addition; i.e., the sum of
two rationals is still rational. From this property we can conclude that the
sum of three rationals is rational, and so on. Therefore, the sum of any
nite number of rationals is rational, but the sum (5.1) contains an in nite
number of terms! But equally, this fact alone is not suÆcient to demonstrate
that a number is not rational. For instance, the decimal expansion of 1=3
1 3 3 3
= 0:33333 : : : = 1 + 2 + 3 +   
3 10 10 10
is structurally identical to that of , but in this case the value of an in nite
sum of rationals is rational.
Before clarifying this point we develop the Maple tools for generating
decimal expansions. Maple provides the standard library function evalf,
which turns a number into a string of decimal digits. The default number of
digits is equal to ten, which is the value of a Maple constant called Digits.

> Digits;
10

> Pi,evalf(Pi);
; 3:141592654
> Digits:=20:
> evalf(Pi),evalf(Pi,3);
3:1415926535897932385; 3:14
5.1. DIGITS OF RATIONALS 91

Note the possibility of overriding temporarily the default value of Digits,


with the optional second argument of evalf.
We remark that for a given accuracy, not all displayed digits are neces-
sarily exact, since they are chosen in such a way as to minimize the error.
For instance, the tenth decimal digit of  is 3, but since  is closer to
3:141592654 than to 3:141592653, when Digits is set equal to 10, the last
displayed digit is 4. The following example is even more dramatic
> 0.099991:
> %,evalf(%,4),evalf(%,3);
:099991; :09999; :100
When the accuracy is reduced to three digits, none of the displayed digits
is correct!
We begin with some experiments on digits of rationals. As we need to
gather clear evidence, we set a large value of the constant Digits
.> Digits:=50:
> 9/176:%=evalf(%);
9
= :051136363636363636363636363636363636363636363636364 (5.2)
176
> 11/101:%=evalf(%);
11
= :10891089108910891089108910891089108910891089108911 (5.3)
101
> 999999/1048576:%=evalf(%);
999999
= :95367336273193359375000000000000000000000000000000
1048576
(5.4)
> 15/17:%=evalf(%);
15
= :88235294117647058823529411764705882352941176470588 (5.5)
17
The common feature of these decimal expansions is the existence of a
block of digits that appears to repeat inde nitely. This block is 36 in (5.2),
1089 in (5.3), 0 in (5.4), and 8823529411764705 in (5.5). Repetition does
not necessarily set in from the very beginning, but it may be preceded by
a non-repeating block, which is 0511 in (5.2) and 95367336273193359375
in (5.4). In the remaining examples, there is no such non-repeating block.
These observations can be summarized by saying that the digits of a rational
number appear to be eventually periodic (see section 4.4). This is indeed
true, as detailed in the next two theorems.
Theorem 3 A number is rational if and only if its decimal digits are even-
tually periodic.
92 CHAPTER 5. REAL AND COMPLEX NUMBERS

We analyze the statement of this theorem in some detail. We know that


the elements of Q are ratios of integers. Let us denote by P the set of all
numbers whose decimal expansion is eventually periodic. The theorem says
that P = Q , thereby establishing an alternative way of de ning the set Q .
This statement consists of a two-way implication, expressed with the
condition `if and only if'. The rst implication, `a number is rational if
its digits are eventually periodic' means that eventual periodicity implies
rationality
x is rational (= the digits of x are eventually periodic
which we write formally as
x2Q (= x 2 P:
By de nition, this means that P  Q (cf. (3.7)). Note that stating that P
is a subset of Q does not necessarily imply that P is properly contained in
Q . It just means that every element of P is also an element of Q .
The if implication alone does not rule out the possibility that some
rational number has non-repeating digits. To ensure that such a possibility
does not actually occur, we need the converse implication `a number is
rational only if its decimals are eventually periodic', which states that
rationality implies eventual periodicity
x is rational =) the digits of x are eventually periodic
or, equivalently,
x 2 Q =) x 2 P;
which now says that Q  P (cf. (3.8)). The two inclusion relations put
together give
x 2 Q () x 2 P
which is the de nition of equality between sets: P = Q . We shall give a
constructive proof of the (= implication below. The proof of =) will be
proposed as an exercise.
The next result provides detailed information on the structure of the
digits of a rational.
Theorem 4 Let r = p=q be a rational number with p and q coprime and
0  r  1. Then the decimal expansion of r consists of m pre-periodic
digits followed by n digits which repeat themselves inde nitely. Letting
q = 2a5b R gcd(10; R) = 1
we have that m = max(a; b). As to n, we have two cases:
(i) If R > 1, then n is the smallest integer for which 10n gives remainder
1 when divided by R. (In particular, n < R).
5.1. DIGITS OF RATIONALS 93

(ii) If R = 1, then n = 1, and r has two decimal representations, where the


repeated digit is 0 and 9, respectively.
Note that case (ii) corresponds to the denominator q being divisible only
by 2 or 5. We can see the theorem in action in the examples we have
illustrated above. Take the case p=q = 9=176. Numerator and denominator
are coprime, or Maple would have eliminated any common factor. We factor
the denominator
> ifactor(176);
(2)4 (11)
and in the notation of Theorem 4, we have a = 4; b = 0, and R = 11. Thus,
m = 4, and n < 11. To determine the actual value of n, we consider powers
of 10, and note that 101 = 0  11 + 10 and 102 = 9  11 + 1, so 2 is the
smallest power of ten which gives remainder 1, modulo 11, whence n = 2.
Computing the digits of a rational
We describe an algorithm for computing the digits of a rational number
r = p=q, which makes use only of the arithmetic in Q . Without loss of
generality we may assume that 0  r < 1. We begin by writing out the
decimal expansion of r
p
r = = 0:d1 d2 d3    0  dk < 10; k = 1; 2;    : (5.6)
q
We are interested in identifying the nth digit dn of r. Multiplying r by 10n
amounts to shifting the decimal digits of r to the left by n places
10nr = d1 d2    dn :dn+1 dn+2 dn+3    = d1 d2    dn + 0:dn+1 dn+2 dn+3   
The integer d1 d2    dn is the integer part of 10n p=q, namely the quotient
of the integer division of 10np by q. Dividing such an integer part by 10
leaves remainder dn , which is the desired digit (think about it). Thus,
> dgt:=(r,n)->irem(iquo(10^n*numer(r),denom(r)),10):
> evalf(5/13);(seq(dgt(5/13,n),n=1..10));
:3846153846
3; 8; 4; 6; 1; 5; 3; 8; 4; 6
A variant of the above algorithm provides a constructive proof that the
digits of a rational must eventually repeat. With reference to equation
(5.6), we multiply r by 10, causing the rst digit d1 to be moved to the left
of the radix point
10r = d1 :d2 d3 d4 : : :
Then d1 | the rst digit of r | is the integer part of 10r. To extract the
second digit of r we consider the number
r2 = 10  r d1 = 0:d2 d3 d4 : : :
94 CHAPTER 5. REAL AND COMPLEX NUMBERS

and then repeat the same process as before.


We carry out this iterative procedure explicitly, and show that it even-
tually leads to repetition. Let r = r1 = p1 =q. Then the condition 0  r < 1
implies 0  p1 < q, and
10p1 p
10r1 = = d1 + 2 = d1 + r2 :
q q
The integer p2 | the remainder of division of 10r by q | is uniquely
determined by p1 , and 0  p2 < q. Repeating this process, we obtain a
sequence of integers p1 ; p2 ; : : :, all lying between 0 and q, and such that pk
is uniquely determined by its predecessor pk 1 .
In other words, the sequence p1 ; p2; : : : is a recursive sequence of ele-
ments of the set D = f0; 1; 2; : : : ; q 1g, whose initial condition p1 is the
numerator of the rational in question. But since D has a nite number of
elements, after at most jDj = q iterations the integer pk will necessarily
assume a value assumed before (why?). From that point on, its values will
begin to repeat, and with them the digits of r.
As an example, we compute the digits of 1=7.
10  1 = 1 + 3
7 7
10  3 = 4 + 2
7 7
10  2 = 2 + 6
7 7
10  6 = 8 + 4
7 7
10  4 = 5 + 5
7 7
10  5 = 7 + 1
7 7
Thus, the repeating digits of 1=7 are 142857, without a non-periodic head.
We implement the above recursion in Maple
> p:=1:q:=7:iquo(10*p,q);
1
> p:=irem(10*p,q):iquo(10*p,q);
4
> p:=irem(10*p,q):iquo(10*p,q);
2
The above computation is ineÆcient, because in a single call to iquo or
irem, Maple computes both quotient and remainder. A nice way of solv-
ing this problem is to call iquo with the optional third argument 'p' (see
section 2.7). In this way the value of irem(10*p,q) is computed and au-
tomatically assigned to p.
5.1. DIGITS OF RATIONALS 95

> p:=1:q=7:
> seq(iquo(p*10,q,'p'),k=1..7);
1; 4; 2; 8; 5; 7

Exercises
Exercise 5.1. Consider the following rational numbers r
10001 13 1
(i) (ii) (iii) :
11110 23 585728
Let m be the number of the pre-periodic decimals, and n the period of the
repeating decimals of r.
(a) For each value of r, evaluate a suÆcient number of decimal digits, and
hence conjecture the values of m and n. Identify the pre-periodic head of
m digits, as well as the n repeating digits of the tail.
(b) Express the denominator of r in the form 2a 5bR, where R is relatively
prime to 2 and 5. Compute m from a and b, and check that for R > 1 you
have n < R.
(c) Summarize your results in a table.
(d) For the case (ii) determine the third digit of r using only the functions
irem and iquo.
Exercise 5.2. Let x = a=b and y = c=d be rational numbers, in reduced
form. Their midpoint and mediant, given by (x + y)=2 and (a + c)=(b + d),
respectively, lie in [x; y] | the interval with endpoints x and y (cf. equations
(2.20) and (2.21)).
(a) Construct a function mid(x,y) whose value is the midpoint of x and
y.
(b) Construct a function med(x,y) whose value is the mediant of (the
reduced formpof) x and y.
(c) Let = 2 1. (You may assume that is not rational.) Show that
lies in [0; 1].
(d) Compute the midpoint r of 0 and 1, using mid, hence decide which
of the two sub-intervals [0; r] or [r; 1] contains . (Convince yourself that
6= r, because r is rational and is not.) Then compute the midpoint of
that interval, and decide which of the two resulting sub-intervals contains
, and so on. Repeat this process until you have determined a rational
number whose distance from is less than 10 2.
(e) Do the same with the mediant in place of the midpoint, using med.
Compare the performance of the two methods with a short comment.
Exercise 5.3 .
 Prove that if the digits of a number are eventually
periodic, then one can nd integers k and m such that 10k + m has
periodic digits.
96 CHAPTER 5. REAL AND COMPLEX NUMBERS

Exercise 5.4 .
 Prove that a number whose digits are eventually periodic
is rational. [Hint: rst prove it in the periodic case, then use the result of
the previous exercise.]

5.2 Real numbers

In the previous section we have identi ed the distinctive feature of the digits
of a rational number, their eventual periodicity. This gives us a constructive
method for building irrational numbers. All we have to do is to produce
strings of digits that do not repeat, some examples of which are given below
(these examples, however, turn out to be atypical, as we shall see)

1 = 0:1234567891011121314151617181920212324252627282930 : : :
2 = 0:4040040004000040000040000004000000040000000040000 : : :
3 = 0:1223334444555556666667777777888888889999999991010 : : :
(5.7)
Putting together the rational numbers (eventually periodic digits) and
the irrational numbers (non-eventually periodic digits), we obtain the set R
of real numbers. Such set is the collection of all decimal expansions having
a nite number of digits to the left of the radix point. Any such expansion
de nes an in nite sum whose value is the real number in question (see
exercises). It should be remembered that the correspondence between digit
strings and real numbers fails to be bi-unique in the case of rationals whose
denominator is divisible only by 2 or 5, which have two distinct expansions.
This ambiguity gives rise to quite a lot of problems in numerical analysis,
the branch of computing concerned with manipulating real numbers.
Because R contains Q , we have the chain of inclusions
N  Z Q  R:
The arithmetical operations in R can be de ned, for instance, as the limit
of operations on rationals, but we shall not be concerned with this problem
here. All we need to note is that, like in Q , in R we can perform all four
arithmetical operations unrestrictedly, excluding division by zero. So R,
like Q , is a eld.
A distance in R
We de ne a distance in R in the same way as we did in Q . The distance
between two real numbers x and y is de ned as the size of the real number
x y, which is jx yj. If two real numbers share the beginning of their
sequence of digits, then they are close to each other: the larger the number
of common digits, the closer they are. For instance, let us consider the
three numbers
 = 3:14159265358979 : : :
r1 = 3:14158430114199 : : :
r2 = 3:14159265359001 : : :
5.2. REAL NUMBERS 97

We see that r1 has 4 digits after the decimal point in common with , while
r2 has 9 of them. We nd
j r j1 = 0:000008 : : : ' 10 5
j r j2 = 0:00000000008 : : : ' 10 10

The converse is not true: two real numbers may be very close to each
other without sharing any digit at all. This phenomenon originates from
the fact that certain rationals have two distinct decimal representations
(cf. Theorem 3.2). If x is one such rational, then closeness to x means
identi cation of the digits of one of the two representations, that is
x = 12 = 0:500000000000000 : : : = 0:499999999999999 : : :
r1 = 0:50008430114199 : : :
r2 = 0:49999999999001 : : :
Thus, r2 is closer to 1=2 than r1 .
Real numbers in Maple
A real number in Maple is a decimal number with radix point and sign.
The positive sign may be omitted.
> 1.5, -33.0, 0.0001, +41.41;
1:5; 33:0; :0001; 41:41

> seq(whattype(x),x=%);
float; float; float; float
The above syntactical construction with seq is novel, since the running
index x is extracted from the elements of an arbitrary expression sequence,
rather than from a range. The expression sequence can also appear directly
as the second argument of seq, but in this case it must be enclosed in
parentheses, because a call to seq requires two arguments.
> seq(whattype(x),x=(1.5,-33.0,0.0001,+41.41));
We shall return to this point in section 6.3.
The word oat denotes the oating-point data type, which refers to the
way these data are represented in Maple (see below).
Very large or very small real numbers are more conveniently written in
exponential notation, which mimics more closely the way these numbers are
represented. The syntax is the following
xey ! x10y
where x is a real or an integer, y is an integer, and they are separated by
the character e. This corresponds to multiplying x by 10y . Thus, 1.5e-4
represents the number 1:5  10 4 = 0:00015.
98 CHAPTER 5. REAL AND COMPLEX NUMBERS

> 1.5e-4,1.5e4,1.5e-20,1.5e20;
:00015; 15000:; :15 10 19; :15 1021
The function evalf can be used to transform integer or rational data types
(among others) into the oating-point type
> 3,1/3,evalf(3),evalf(1/3);
1
3; ; 3:; :3333333333
3
Expressions such as 3. and .3 are valid real numbers, but their use is
discouraged because the radix point is easily overlooked, as illustrated in
the following example
> (1+2)/(3+4)*5+6-7/8;
407
56
> (1+2)/(3+4)*5+6-7/8.;
7:267857143
Note that the oating-point data type is `contagious'. The presence of the
single real number 8. forces the whole expression to become real.
The oating-point representation is non-exact, since a computer cannot
store in nitely many digits. It should be noted that while integers and
rationals can also be represented as oating-point numbers, the two repre-
sentations are vastly di erent. Every oating-point number is represented
as a pair of integers, called the mantissa and the exponent.
3:141592654 = mantissa  10 exponent = 3141592654  10 9
Mantissa and exponent are operands (that is, components) of the expression
representing the real number
> op(evalf(Pi));
3141592654; 9
The function op returns the operands of an expression (see chapter 6).
We compare the representations of 1=3 as a rational and as a real, with
10 digits accuracy
> op(1/3);op(evalf(1/3));
1; 3
3333333333; 10
This result says that
1
3
' 3333333333  10 10
We stress again that the oating-point representation is only approximate
> 3*(1/3),3*evalf(1/3);
1; :9999999999
5.3. RANDOM AND PSEUDO-RANDOM DIGITS
 99

Exercises
Exercise 5.5. The following numbers are rational approximations to  =
3:1415 : : :
22 314 333 355 355 103993 31415926
; ; ; ; ; ; : (5.8)
7 100 106 113 114 33102 10000000
(a) Create a Maple list whose elements are these numbers.
(b) De ne a Maple function d(x), which returns the distance between x
and : d(x) = jx j.
(c) Compute the distance between  and every element of the sequence
(5.8), whence order the elements of the sequence (5.8) according to how
well they approximate  (begin with the worst approximation).
Exercise 5.6. Let be a real number, and let
1
g(x) = e (x 2) :
6
f (x) = x
2
For certain values of , the equation f (x) = g(x) admits three solutions,
which correspond to three intersections of the graphs of f and g. These
values of form an interval [a; b]. Plot f and g in the same plot, for various
values of of your choice, and by examining the graphic data determine
approximate values for a and b (10% accuracy will suÆce).
Exercise 5.7. Let D be a positive integer. We consider the following
recursive sequence of rational numbers
x2 + D
x0 = 1 xt+1 = t ; t  0:
2 xt
p
It can be shown that the elements of this sequence approach D very
quickly. This method for computing the square root is called Newton's
method.
Usingp the pabove sequence twice, determine a rational number approxi-
mating 2 + 3 with an error not greater than 10 5.
Exercise 5.8 .
 Prove that any decimal expansion with nitely many dig-
its to the left of the radix point de nes a unique number (you must prove
the convergence of a series).

5.3 Random and pseudo-random digits

The examples of irrational numbers that were given in (5.7) are, in a sense,
misleading. There are obvious patterns in their digit sequences. The knowl-
edge of such patterns can be exploited to specify these numbers concisely,
using a very small amount of information. For instance, the number 1
is the real number whose digits are given by the sequence of all positive
100 CHAPTER 5. REAL AND COMPLEX NUMBERS

integers. Likewise, the number 2 is de ned by the rule that its nth digit
is equal to 4 if n is a number of the form n = k(k + 1)=2 (a triangular
number), and to 0 if it is not, etc. These de nitions could be translated
into computer programs that generate these numbers to any desired degree
of accuracy.
However, the digits of a real number are not subject to any constraint,
in the sense that any sequence of digits de nes a unique number. So, if we
choose a number blindly, we should expect its digit sequence to be not only
aperiodic, but also patternless. The validity of this observation is con rmed
by a celebrated theorem of complexity theory, which states that almost all
numbers have random digits.
The expression `almost all' is to be intended in a probabilistic sense: a
blind choice will give you a random number unless you are extremely lucky
(or extremely unlucky, depending upon which way you look at it). Said
di erently, if you take all possible strings of n digits, where n is a large
integer, those that are not random form a vanishing fraction of the total.
Randomness is the property we usually associate to the outcome of
a gambling device. Loosely speaking, a sequence of digits is said to be
`random' if the most economical way of specifying its elements is to list
them all explicitly, one by one. So a sequence is random if the information
it contains cannot be compressed in any way. Any computer program that
generates the rst n bits of a random sequence cannot itself be shorter than
n bits, lest we would have achieved a compression of information stored in
the sequence.
To illustrate this concept, suppose we have to send to a distant galaxy
the rather dull sequence consisting of the rst billion odd integers, and
suppose that the cost of the transmission is very high. It is quite possible
to minimize the amount of transmitted data: instead of sending the entire
sequence, we send the Maple statement seq(2*i-1,i=1..10^9);. This
is a compressed version of the same information (21 characters in all!),
which the receiver can decode, recovering the original information. This
substantial data compression was made possible by the very non-random
nature of our sequence. But if we had to transmit, say, the outcome of all
football games since the beginning of the century, one can see that it is
going to cost a lot more.
We seem to have reached an impasse. If we are to build a very long string
of digits, then we need some kind of algorithm | a sequence of computer
instructions to be repeated automatically. However, the very existence of
such algorithm makes the outcome non-random, according to our de nition
of randomness. It then appears that a truly random sequence cannot be
meaningfully de ned, represented, computed, or predicted: it is terminally
beyond our grasp. But then, how close can one get to observing randomness
inside a computer? What a machine can generate are the so-called pseudo-
random numbers: they `look like' random numbers, but they are actually
5.3. RANDOM AND PSEUDO-RANDOM DIGITS
 101

produced by programs which are often small and fast.


To see how this could be achieved one does not have to go too far,
because pseudo-randomness is ubiquitous in arithmetic. Even the digits of
a rational number before they start repeating already possess a considerable
degree of unpredictability. For instance, the repeating block of digits of
any rational with prime denominator 47 happens to be 46 digits long. By
varying the numerator, we have an easy method for constructing nite
pseudo-random sequences
> evalf(6/47,46);evalf(13/47,46);evalf(36/47,46);
:1276595744680851063829787234042553191489361702
:2765957446808510638297872340425531914893617021
:7659574468085106382978723404255319148936170213
We see that the above sequences are cycling permutations of the same
basic sequence, with the numerator determining the starting point. A very
popular type of pseudo-random number generators employs a variant of the
above principle (check Maple's facilities on random number generators by
typing ?rand).
An even more dramatic
p illustration is o ered by the digits of the square
root of two. Because 2 is irrational (see below), its digits never repeat.
We display the rst 50 of them
> sqrt(2)=evalf(sqrt(2),50);
p
2 = 1:4142135623730950488016887242096980785696718753769
and note that they have a random avour. However, this number is de ned
by a tiny amount of information: it is one of the p two solutions of the
polynomial equation x2 = 2, the other being 2 (incidentally, that's
how Maple represents it). Therefore, according to our previous de nition,
we are not allowed to call these digits random. Does it mean that some
pattern must exist? None has been found p so far, and, moreover, there are
several phenomena related to the digits of 2 which carry the signature of
randomness. Is our de nition of randomness appropriate
p then? The fact is
that the question `how random are the digits of 2?' remains unanswered,
and so do many deep problems surrounding pseudo-randomness. For an
introduction to the modern notions of deterministic randomness and chaos,
see Reference [6]. p
We conclude this brief exploration of 2 by proving that it is irrational,
which implies that its digits do not repeat. Establishing irrationality of a
given real number is usually very diÆcult, but in this case we can prove it
without much e ort.
p
Theorem 5 2 62 Q .
102 CHAPTER 5. REAL AND COMPLEX NUMBERS

p
Proof.pAssume 2 is rational. Then there exist two integers a and b such
that 2 = a=b, and we shall agree that a and b are relatively prime (if
they are not, we rst divide by their greatest common divisor). Squaring,
we obtain 2b2 = a2 , whence a2 is even. From the fundamental theorem of
arithmetic, we can then conclude that a is even (why?), and we let a = 2k.
But then 2b2 = (2k)2 = 4k2 and so b2 = 2k2 , and with the same reasoning
we conclude that also b is even. But this is impossible,
p because a and b
were assumed to have no common divisor. So 2 is irrational.

This is an example of proof by contradiction. We have assumed the


opposite of what we wanted to prove, and we have arrived at an internal
inconsistency in the argument
p
2 is rational =) two relatively prime integers are even.
This necessarily means that the statement on the left of the implication
=) is false, that is, that its negation is true.

5.4 Complex numbers

There are still arithmetical problems in R, and they originate from the fact
that the square of a real number cannot be negative. Suppose that this was
p py and a positive real number
not true, and that we could nd a real number
a such that y2 = a. Then by writing a = a a, and letting x = y= a, we
p
would have a real number x (why real?) satisfying the equation x2 = 1, a
nice quadratic equation with integer coeÆcients. So all problems in R can
be traced to the impossibility of solving the equation x2 = 1, for a real
number x. We have experienced similar problems in Q , when we attempted
to solve equations like x2 = 2. That led to the introduction of R.
A solution of the equation x2 = 1 is `a thing whose square is equal to
minus one', which is often called the imaginary unit and denoted by the
letter i. We shall not attempt to ascertain what such object actually is;
all we need to know is that if we square it, we get 1. If we assume that
i obeys ordinary arithmetical rules, we must then conclude that i also
satis es the same equation, since ( i)2 = ( 1)2 i2 = 1  i2 = 1. We have
i0 = 1; i1 = i; i2 = 1; i3 = i; i4 = 1; etc: (5.9)

p i,1namely
That is, the sequence of powers of ik ; k = 0; 1; 2; : : : is periodic
with period 4. Maple represents by the symbol I and we can easily
generate a few terms of this sequence, to emphasize its periodicity
> seq(I^k,k=0..12);
1; I; 1; I; 1; I; 1; I; 1; I; 1 I; 1
5.4. COMPLEX NUMBERS 103

This is not the rst time we nd a number whose powers form a periodic
sequence. The powers of the integers 1 and 1 also generate periodic
sequences, with period 1 and 2, respectively
> seq((-1)^k,k=0..12);
1; 1; 1; 1; 1; 1; 1; 1; 1; 1; 1 1; 1
So far we have considered i in isolation. Now we combine it with ele-
ments of R, beginning with expressions of the type
z = r0 + r1 i + r2 i2 + r3 i3 + r4 i4 +    + rn in rk 2 R:
Because of (5.9), this expression becomes
z = r0 +r1 i r2 r3 i+r4 +r5 i+    = (r0 r2 +r4   )+i (r r +r   ):
1 3 5

The term in the rst set of parentheses is a nite sum of real numbers, and
it is therefore a real number. (In nite sums may also be meaningful, but
their study transcends the scope of this course.) The same holds for the
sum in the second set of parentheses, and so z is of the form
z = r + is r; s 2 R : (5.10)
The real numbers r and s are called the real part and imaginary part of z ,
respectively.
Next we consider the four arithmetical operations with expressions of
the type (5.10). Let z = r + is and w = t + iu. We have
z  w = r + is  t  iu = (r  t) + i (s  u)
zw = (r + is)(t + iu) = (rt su) + i (ru + ts)
z r + is (r + is)(t iu) (rt + su) + i (st ru) (5.11)
w = t + iu = (t + iu)(t iu) = t2 + u2
rt + su
= 2 2 + i 2 2: st ru
t +u t +u
For division to make sense, we must assume that all denominators are
nonzero. For this it is suÆcient to require that w 6= 0, that is, that t and u
are not both zero. This in turn guarantees that the quantity t iu is also
nonzero, and so is the product (t + iu)(t iu) = t2 + u2 .
Equations (5.11) show that all numbers of the form (5.10) form a set
closed under the four arithmetical operations, excluding division by zero.
This is the set C of complex numbers. So C is a eld. We see that C is
obtained from R by adjoining to it the quantity i, and then allowing unre-
stricted arithmetical operations between i and the elements of R, assuming
that i obeys ordinary arithmetical rules.
Letting s = 0 in (5.11), we obtain z = r +0  i = r, a real number. Thus,
C contains R, the set of complex numbers with zero imaginary part, and
we have the chain of inclusions
N ZQ  R C : (5.12)
104 CHAPTER 5. REAL AND COMPLEX NUMBERS

As far as `ordinary' numbers are concerned, this is the end of the road.
There is no arithmetical need of going beyond C . The distinguished 19th-
century mathematician L. Kronecker once said:
`God gave us the integers, the rest is the work of man.'

You can begin to see the giant edi ce mathematicians have constructed
from the natural numbers alone. The diÆcult step is the one between Q
and R. In fact, only two integers are needed to construct a rational, and
only two reals are needed to construct a complex number. But in nitely
many rationals are needed to construct a real number. In fact, the domain
lying between Q and R (or C ) is by far the most interesting one, but its
study lies beyond the scope of this course.
The following table summarizes the most signi cant steps in the journey
from N to C . The need of enlarging a set of numbers originates from the
impossibility of solving certain equations.
FROM N TO C
solve solve solve solve
set x+a=b ax = b x2 = a x2 = a
a; b 2 N a; b 2 Z; a 6= 0 a2N a2Z
N no no no no
Z yes no no no
Q yes yes no no
R yes yes yes no
C yes yes yes yes

A distance in C
How do we measure the size of a complex number? The real numbers were
represented geometrically as points on a line, and we de ned their size to
be the distance from the origin. Likewise, complex numbers are points in
the plane, so it is natural to represent the size of a number as its distance
from the origin in C .
If z = x + iy, we let z = x iy. The number z is called the complex
conjugate of z , and from (5.11) we nd
z z = (x + iy)(x iy) = x2 + y2 :
But then, from Pythagoras' theorem, the distance of the point z from the
origin is given by the modulus of z
p p
jz j = z z = x 2 + y2 : (5.13)
Since
(z) = x iy = x + iy = z;
5.4. COMPLEX NUMBERS 105

we have that p p
jzj = zz = zz = jz j:
As we did for Q and then for R, we de ne the distance between two
complex numbers z1 and z2 as the size of their di erence, which is jz1 z2j.
On the plane, the triangle inequality (2.6) justi es its name: it says that
if x, y, and z are complex numbers representing the vertices of a triangle,
then the length of the side connecting x to z cannot be greater than the
sum of the length of the other two sides.
So in C , like in R, there is an arithmetical structure and a distance (but
not an ordering relation ).
Complex numbers in Maple p
We have seen that in Maple the number 1 is represented by the symbolic
name I. The basic operations of complex arithmetic are straightforward,
with several intrinsic functions available for this purpose.
> z:=2-I:
> Re(z),Im(z),conjugate(z),abs(z);
p
2; 1; 2 + I; 5
An expression involving complex numbers with rational real and imaginary
parts is automatically simpli ed to the form x + iy with x; y 2 Q
> z^2+1/z;
17 19
I
5 5
> evalf(%);
3:400000000 3:800000000 I
Note that evalf acts separately on the real and imaginary parts of a com-
plex expression (see also section 6.3).
The simpli cation to the form r + is is not carried out in general. To
achieve it, one must use the standard library function evalc (evaluate to
complex)
> 1/(x+I*y);
1
x+Iy
> evalc(%);
x Iy
x + y2
2
x + y2
2

Example 5.1. Plotting a complex sequence. We want to plot the complex


numbers
1 ni
zn = n = 1; 2; : : :
n + 4 in
106 CHAPTER 5. REAL AND COMPLEX NUMBERS

as points in the complex plane. The data are arranged as a list consisting
of two-element lists [xn ; yn ], where xn and yn are the real and imaginary
part of zn, respectively.
> z:=n->(1-n*I)/(n+4*I^n):
> data:=[seq([Re(z(n)),Im(z(n))],n=1..30)]:
> plot(data);

-0.4 -0.2 0.2 0.4 0.6


0

-1

-2

-3

Exercises
Exercise 5.9. Let z = 11 19i. Compute, with Maple
1=z; z; jz j; arg(z); Re(z ); Im(z ); 1 z2:
where z is the complex conjugate of z .
Exercise 5.10. Which of the following complex numbers
109
z1 = z2 = 7 + 7i z3 = 5 9i z4 = 1 10i
11
is nearest to the origin? Which is nearest to i?
Exercise 5.11. Consider the following recursive sequence of complex
numbers
4 z i
z0 = (9 + i) zt+1 = 8 t ; t  0:
41 i zt + 10
5.4. COMPLEX NUMBERS 107

(a) Show that z1 ; z2 , and z3 lie on a circle centered at the point z = 4 + i,


and determine its radius.
(b) Let zt be as above. Determine the smallest value of t for which zt lies
inside a circle of diameter 1=10 centered at 2i.
Exercise 5.12. Let n be a xed positive integer. Consider the following
sequence of complex numbers
zk = exp(2ik=n) k  0:
(a) Construct a Maple function z(k,n) whose value is zk , hence display
zk in the form xk + iyk .
(b) Prove with Maple that zk lie on the unit circle in the complex plane
(the circle with radius 1 and centre at z = 0).
(c) Let n = 7. Express z1 in the form x1 + iy1, rst symbolically, and then
numerically, with 20 digits of accuracy.
(d) If z = x + iy, from (5.13) we have that
jz j2
= x2 + y2:
Using the above equation and the numerical expression for z1 just com-
puted, verify that jz1 j2 = 1.
(e) Fix n = 5. Plot the points z1 ; z2 ; : : : ; z5 in the complex plane, connect-
ing successive points by segments.
(f ) Plot a regular polygon with 11 sides.
(g) For n = 11, generate and plot the sequence of points
wk = z3k k = 0; 1; : : : ; 11:
Identify w4 on your plot.
(h) By now you should have enough evidence to conjecture that for any
n > 0 the sequence k 7! zk is periodic with period n. This means that for
every integer m, the following holds
zk = zk+mn k  0:
Prove it.
Exercise 5.13. Let the complex numbers z1 = 91 24i and z2 =
200 + 100i be two vertices of a square in the complex plane. There are
three such squares (think about it).
(a) Determine the areas of the three squares.
(b) Construct the three squares and plot them, all in the same plot. (Maple
may scale the two axes di erently, resulting in a distorted picture. To
prevent this from happening, insert the option scaling=constrained as
the last argument of the function plot.)
108 CHAPTER 5. REAL AND COMPLEX NUMBERS

Exercise 5.14. Prove de Moivre's theorem with Maple


n
ei = cos(n) + i sin(n):

5.5 Standard library functions

Maple has several built-in functions for performing the basic operations of
real and complex calculus. The argument of the trigonometric functions is
in radians.
REAL AND COMPLEX FUNCTIONS
Trigonometric, hyperbolic, and logarithmic functions
sin(x),cos(x),tan(x) Sine, cosine, tangent
of the angle in radians.
sec(x),csc(x),cot(x) Secant, cosecant, cotangent.
arcsin(x),arccos(x), Arc sine, arc cosine, arc tangent,
arctan(x) with range in [ =2; =2].
sinh(x),cosh(x),tanh(x) Hyperbolic sine, cosine, tangent.
sech(x),csch(x),coth(x) Hyperbolic secant, cosecant,
cotangent.
sqrt(x) Square root.
exp(x) Exponential function ex.
log(x) Natural logarithm (base e).
log10(x) Logarithm to the base 10.
log[b](x) Logarithm to the base b.
GAMMA(x) Gamma function.
Other functions
abs(x) Absolute value.
sign(x) Sign of x (1 or 1).
max(x,y,: : :) The largest value among arguments.
min(x,y,: : :) The smallest value among arguments.
round(x) Round x to the nearest integer.
trunc(x) Truncate x to its integer part.
floor(x) Floor function bxc.
ceil(x) Ceiling function dxe.
evalf(z,n) Evaluate z to n oating-point digits.
Complex arithmetic
Re(z) Real part of z .
Im(z) Imaginary part of z .
conjugate(z) Complex conjugate of z .
argument(z) Argument of z (principal value).
evalc(z) Split z into real and imaginary part.
5.5. STANDARD LIBRARY FUNCTIONS 109

Di erentiation and Integration


diff(expr,x) Derivative of expr with respect to x.
int(expr,x) Inde nite integral of expr with respect to x.
Example 5.2. Let x be any real expression, whose value is nonzero. The
function
> ndgt:=x->max(0,floor(evalf(log[10](abs(x)))) + 1):
returns the number of decimal digits of the integer part of x.
Example 5.3. Let x be a rational number. Then the expression
iquo( numer(x)),denom(x)) has the same value as floor(x) if x is non-
negative, and as ceil(x), if x is negative.
Example 5.4. The factorial function is well-approximated by the follow-
ing formula  n n p
n! = 2n (5.14)
e
called Stirling's formula. Here e = 2:718 : : : is Napier's constant (the basis
of the natural logarithm), which can be computed with Maple using the
exponential function
> evalf(exp(1),50);
2:7182818284590452353602874713526624977572470937000
The accuracy of Stirling's formula increases as n increases, in the sense
that the relative error vanishes. This means that the ratio between n! and
Stirling's approximation approaches unity.
> Stirling:=n->evalf((n/exp(1))^n*sqrt(2*Pi*n)):
> 10!/Stirling(10),100!/Stirling(100);
1:008365358; 1:000833670
Note that the absolute error | the size of the di erence between the two
quantities | increases inde nitely!
> 10!-Stirling(10),100!-Stirling(100);
30104:378; :7773848155

The gamma function


The gamma function (x) is de ned as the de nite integral
Z 1
(x) = tx 1 e t dt; x > 0: (5.15)
0

The function may be viewed as a generalization of the factorial function.


Speci cally, we now show that if x is a non-negative integer, then (x +1) =
x!.
110 CHAPTER 5. REAL AND COMPLEX NUMBERS

R We replace x by x + 1 in (5.15) and integrate by parts, recalling that


e t dt = e t.
R1 x 1 t
(x + 1) = txR( e t )j10 + 0 xt e dt
1 x
= x 0 t e dt 1 t
= x (x):
Thus, (x + 1) = x (x). If we let (x + 1) = x!, we obtain x! = x  (x 1)!,
which is the recursion relation for the factorial function. To prove that
(x + 1) is indeed equal to x!, we must check the initial condition 0! = 1 =
(1) Z 1 Z 1
(1) = 0 t
t e dt = e t dt = ( e t ) 10
= 1:
0 0

This shows that (x + 1) = x!. Note, however, that the integral (5.15) is
de ned also when x is not an integer.
In Maple, the symbolic name for the gamma function is GAMMA. Maple
knows that the value of at positive integers is an integer. It also knows
the values of at half-integers.
> seq(GAMMA(x),x=1..5);
1; 1; 2; 6; 24
> seq(GAMMA(evalf(x)),x=1..5);
1:; 1:; 2:; 6:; 24:
> seq(GAMMA(x-1/2),x=1..5);
p; 1 p; 3 p; 15 p; 105 p
2 4 8 16
> seq(GAMMA(evalf(x-1/2)),x=1..5);

1:772453851; :8862269255; 1:329340388; 3:323350970; 11:63172840


When handling expressions involving factorials, Maple often converts
factorials to gamma functions.
> n!-1/(n+3)!;
1
n!
(n + 3)!

> simplify(%);
(n + 1) (n + 4) 1
(n + 4)
5.5. STANDARD LIBRARY FUNCTIONS 111

Plotting functions of a real variable


In chapter 4, we introduced the utility function plot, to plot the elements
of a sequence. They were represented as a discrete set of points in the plane,
implemented in Maple as a list consisting of two-element lists containing
the Cartesian coordinates of each point.
Plotting a function of a real variable involves simulating a continuum of
values, which is done by a ne scanning of the domain of the function. The
function plot will now require specifying the function to be plotted and its
domain, as the rst and second argument, respectively. The co-domain is
then adjusted automatically, and so is the frequency with which the domain
is scanned.
In the following example, we plot a function displaying rapid oscillations

> plot(sin(x)*sin(10*x)*sin(100*x),x=0..Pi);

0.5

0 0.5 1 1.5 2 2.5 3


x

-0.5

-1

To gain information on the detailed structure of our function, we resort


to magni cation. This is achieved by a suitable compression of the do-
main and the co-domain of the function, the latter entered as an additional
argument of plot
> plot(sin(x)*sin(10*x)*sin(100*x),x=0..0.5,y=-0.5..0.5);
112 CHAPTER 5. REAL AND COMPLEX NUMBERS

0.4

0.2

0 0.1 0.2 0.3 0.4 0.5


x

-0.2

-0.4
Chapter 6

Structure of expressions
In previous chapters, we have encountered a variety of data types, e.g.,
> 3,2/3,2.95,joe,[a,b],fa,bg:
> seq(whattype(x),x=%),whattype(%);
integer; fraction; float; symbol; list; set; exprseq
In this chapter, we consider the way Maple represents composite data, of
which sets and lists are simple examples. In particular, we analyze in detail
the sum, product, and exponent data types, which are used to represent al-
gebraic expressions. This chapter is more technical than mathematical, but
it is necessary for the arithmetic of polynomials and rational functions, and
for understanding the behaviour of certain functions acting on expressions,
such as map, seq, select, etc.

6.1 Analysis of an expression

How does Maple represent an expression such as a + 2bc b3 ?


> x:=a+2*b*c-b^3;

x := a + 2bc b3 (6.1)
> whattype(x);
+
In the rst instance, Maple regards x as a datum of the sum type. To list
the operands of this expression, we use the function op
> op(x);
a; 2bc; b3
> whattype(%);
exprseq

113
114 CHAPTER 6. STRUCTURE OF EXPRESSIONS

Thus, x is represented as the sum of the three operands a, 2bc, and b3 .


Graphically

a + 2bc b3

(+)
. # &
a 2bc b3

Figure 6.1: Graphical representation of the expression a + 2bc b3 : it is of


type + and has three operands.

The standard library function op is a general-purpose function for the


analysis of an expression. The command
> op(expression );
returns the operands of an expression in the form of an expression sequence.
The function op has a rst optional argument. The command
> op(n , expression );
returns the nth element in the sequence of operands of expression.
> op(2,x);
2bc
The rst argument of op can also be a range
> op(2..3,x);
2bc; b3
We continue analyzing expression (6.1), by looking individually at its
operands
> left:=op(1,x):
> middle:=op(2,x):
> right:=op(3,x):
The leftmost operand a has no inner structure | its data type is primitive
> left,op(left),whattype(left);
a; a; symbol
and its analysis is complete. The middle operand 2bc is an expression of
the product type, consisting of three operands
> whattype(middle);

6.1. ANALYSIS OF AN EXPRESSION 115

> op(middle);
2; b; c
These operands are primitive
> seq(whattype(z),z=%);
integer; symbol; symbol
The rightmost operand is also a product
> whattype(right);

> op(right);
1; b3
> seq(whattype(z),z=%);
integer; ^
The expression b3 is an exponent, with operands b and 3
> op(op(2,[%%]));
b; 3
(The use of square brackets is necessary here, lest the innermost op would
have been called with the wrong number of arguments.) The above sub-
expressions are represented as

2bc b3 b3

() () (^)


. # & . & .&
2 b c 1 b3 b 3

Figure 6.2: Representations of the sub-expression 2bc, b3 , and b3 , respec-


tively. Note that b3 is a sub-expression of b3 .

The analysis of the expression (6.1) is now complete. Assembling the


gures (6.1) and (6.2), we obtain the structure depicted in gure 6.3, which
is called a tree.
For some composite data types (e.g., lists, sets), the selection operator
[ ] may be used as a variant of op, with a slightly di erent behaviour
> L:=[one,two,three]:
> L[3],op(3,L),L[1..2],op(1..2,L),L[1..1];
116 CHAPTER 6. STRUCTURE OF EXPRESSIONS

a + 2bc b3

(+)
. # &
a 2bc b3

() ()
.#& .&
2 b c 1 b3

(^)
.&
b 3

Figure 6.3: The tree associated with the complete representation of the
expression a + 2bc b3 .

three; three; [one; two]; one; two; [one]


We see that if the selection is performed by specifying a range, the selection
operator will reassemble the selected operand into the original data type.
In addition, the selection operator may be used to assign a new value to an
element of the list
> L[2]:=TWO:
> L;
[ one; T W O; three ]
However, direct assignment to elements of a list is not eÆcient and should
be avoided. To modify a list, it is preferable to construct a copy of the
original list, using subsop (see section 6.2 and online documentation on
subsop and selection).
The standard library function length (see section 2.7), when applied
to an arbitrary expression, will compute recursively the length of each
operand, and then add up the result. This quanti es the size of the ex-
pression, although the result is not always obvious
> length(12345),length(12345*x),length(x->x^2);
5; 9; 28
6.2. MORE ON SUBSTITUTIONS 117

6.2 More on substitutions

The standard library function subs substitutes expressions with other ex-
pressions. The expression to be changed must appear as an operand of the
original expression or of one of its sub-expressions. The following exam-
ples illustrate how subs operates, depending on the structure of the target
expression.
> expr1:=x*y+z:
> expr2:=x*y*z:
> whattype(expr1),whattype(expr2);
+; 
> op(expr1);op(expr2);
xy; z
x; y; z
Note that xy is a sub-expression of expr1 but not of expr2.

xy + z xyz

(+) ()
. & . # &
xy z x y z

Figure 6.4: Representation of xy + z and xyz . Only xy + z contains xy as


a sub-expression.

Hence
> subs(x*y=joe, expr1);
joe + z
> subs(x*y=joe,expr2);
xyz
To replace xy in expr2, we must resort to a trick
> subs(x=joe/y, expr2);
joe z
We consider another example
> beta:=a*b*c+b*c+(b*c)^3;
:= abc + bc + b3 c3
118 CHAPTER 6. STRUCTURE OF EXPRESSIONS

> op(beta);
abc; bc; b3 c3
Note that the expression bc does not appear as a sub-expression of the third
operand, due to simpli cation.
> subs(b=y,beta);
ayc + yc + y 3 c3

> subs(b*c=y,beta);
abc + y + b3 c3
In order to target the substitution to a particular operand of an ex-
pression, we use the standard library function subsop, which substitutes
speci ed operands with new values
> subsop(3=three, beta);
abc + bc + three
The data type fraction is reserved for rationals. An algebraic fraction
is instead regarded as a product
> 2/3:whattype(%),op(%);
fraction; 2; 3

> a/b:whattype(%),op(%);

; a; 1b
> op(3,[%]):whattype(%),op(%);
^; b; 1
Thus, a=b is represented as a  b 1 .

Exercises
Exercise 6.1. Construct the tree representation of the following algebraic
expressions
2 z
(1) 2 (2) xy (3) xyz + w
y w

(4)
pxy xz + yzw (5) q
x y
(6)
x
p z :
z+ w y+
w
6.3. FUNCTIONS ACTING ON OPERANDS OF EXPRESSIONS 119

Exercise 6.2. Construct the tree representation of the following Maple


expressions
(1) [2,3,f2*3g] (2) seq(i+x,i=1..n)
(3) 33^22<22^33 (4) [x,[y],[[z]]]
(5) f[[],([])],fgg (6) igcd(22,igcd(a,b))
(7) A union (B intersect C) (8) x->fop(1,x)g
Exercise 6.3 .
 Explore the tree representation of a factored integer, de-
signed to prevent automatic expansion of the factors.

6.3 Functions acting on operands of

expressions

Several standard library functions make implicit use of the operand function
op, by acting in various ways on the operands of an expression. Here
we consider seq, map, select, remove, evalf. Other functions acting on
operands (add, mul, sum, prod) will be dealt with in chapter 8.
In chapter 4, we learned that the second argument of the function seq
is either a range, which is expanded to an expression sequence, or an ex-
pression sequence itself. Such argument, however, can be virtually any
expression, which Maple turns into the expression sequence consisting of
its operands at the top level. This feature makes seq into one of the most
useful utility functions in Maple. For instance, the following function re-
turns an expression sequence consisting of the square of all operands of an
arbitrary expression
> sqall:=x->seq(z^2,z=x):
> sqall([a,b,c,d,e]);
a2 ; b2 ; c2 ; d2 ; e2
> sqall(a^2+b*c);
a4 ; b2 c2
An expression sequence can be used as the second argument of seq, pro-
vided it is enclosed in parentheses
> seq(z-1,z=(1,2*4,joe));
0; 7; joe 1
The parentheses are not needed if the expression sequence is represented
symbolically by a variable (including a ditto variable)
> es:=1,8,joe:
> seq(z-1,z=es);
120 CHAPTER 6. STRUCTURE OF EXPRESSIONS

0; 7; joe 1
In chapter 3, we have introduced the construct map(f,A) to obtain the
image of a set A under a function f. The standard library function map
allows for more general usage. Its second argument can be any expression,
not just a set: map will then act on its top-level operands, while preserving
the data type. It is instructive to compare the behaviour of the functions
map and seq when called with similar arguments
> f:=x->x^2:
> map(f,a+b+c);
a2 + b2 + c2
> seq(f(s),s=a+b+c);
a2 ; b2 ; c2
While map preserves the structure of the expression, seq transforms it into
an expression sequence.
If the rst operand f of map requires more than one argument, then
the additional arguments x2 ; x3 ; : : : must be supplied after the target ex-
pression: map(f,expr,x2,x3,..). For illustration, we consider a list L
containing numerical data. We wish to replace any element of L which is
larger than the last element by the latter. This is accomplished by the
following function
> cap:=L->map(min,L,op(nops(L),L));
> cap([1,2,3,4,5,6,7,5]);
[1; 2; 3; 4; 5; 5; 5; 5]
The last element of the list L is given by op(nops(L),L). The rst argument
of the function min runs through all the elements of L, while the second
argument is supplied as the rst optional argument of map.
Another useful utility function is select, which selects the operands
of an expression, according to some criteria. The latter is speci ed by a
Boolean function, which is applied to all operands of the target expression.
The operands giving the value true are those to be selected. The target
expression is usually a list or a set.
To compute the primes between a and b, we rst construct the list of
integers between a and b, which is [$a..b], and then select the primes in
the list with the Boolean function isprime.
> select(isprime,[$100..110]);
[101; 103; 107; 109]
The output is a list, the same data type of the second argument of select.
The syntax of select resembles that of map. Its basic form is select(f,
expr), where f is the symbolic name of a Boolean function (or an explicit
6.3. FUNCTIONS ACTING ON OPERANDS OF EXPRESSIONS 121

function de nition using the arrow operator), while expr is an arbitrary


expression. The function select returns an expression of the same data
type as expr, containing only the selected operands. If the process of
selection is such as to change the data type of expr, an error termina-
tion will occur. As for map, if f requires more than one argument, then
the additional arguments x2 ; x3 ; : : : must be supplied after the target ex-
pression: select(f,expr,x2,x3,..). The following function selects the
non-negative operands of an arbitrary expression
> NonNeg:=A->select(x->evalb(x>=0),A):
> NonNeg(f-3,5,0,-33g);
f0; 5g
The function remove, which is complementary to select, removes (rather
than selects) the operands which match given criteria. Its syntax is iden-
tical to that of select. It is plain that everything that can be done with
remove can also be done with select, and vice versa. For instance, if L is
a list of integers, the expressions
> remove(isprime,L);
> select(x->not isprime(x), L);
will have the same value.
The function evalf also acts on operands, but it does so more selectively
than map, seq, or select.
> evalf(33*x^(1/3)+22*x/4-13/5);
33: x1=3 + 5:500000000 x 2:600000000
Note that evalf has converted into float only the coeÆcients of the
above algebraic expression, leaving the exponent unevaluated. The func-
tion evalf will act in a similar fashion on the real and imaginary part of a
complex number.
Example 6.1. Let L = [ [x1 ; y1 ]; : : : ; [xn ; yn ] ] be a list of points in the
Cartesian plane. The following function returns the list [x1 ; : : : ; xn ] of the
corresponding x-coordinates
> xcoord:=L->map(p->op(1,p),L):

Example 6.2. We generate the set of the irreducible factors of the poly-
nomial x12 1
> fseq(f,f=factor(x^12-1))g;

x 1; x2 + 1; x + 1; x4 x2 + 1; x2 x + 1; x2 + x + 1
The above method would not work for the polynomial x4 + 1. Why?
Example 6.3. Let x be a real number, and let A be a set (list) of real
numbers. We construct a function of x and A whose value is the subset
(sublist) of A constituted by all the elements of A that are smaller than x.
122 CHAPTER 6. STRUCTURE OF EXPRESSIONS

> L:=(x,A)->select((y,x)->evalb(y < x),A,x):


> A:=f3,44,-2,7,23,0,-34g:
> L(7,A);
f0; 2; 3; 34g
p
If A contains symbolic data (i.e.,  or 2), then the Boolean expression
performing the selection will have to be modi ed to evalb(evalf(y < x)),
in order to be evaluated. The following variant of the above construct uses
nops to count the elements of an arbitrary expression A that are equal to
x.
> N:=(x,A)->nops(select((y,x)->evalb(y=x),A,x):

Example 6.4. We construct a function which returns the number of twin


prime pairs (p; p + 2) where p lies between a and b and a  b (see (3.6)).
The relevant Boolean function selects those integers x such that x and x +2
are both primes. The counting is done by nops.
> ntwins:=(a,b)->
> nops(select(x->isprime(x) and isprime(x+2), [$a..b])):
> ntwins(100,200);
7
Example 6.5. The following is a homemade version of the intrinsic func-
tion intersect, computing the intersection between two sets.
> MyIntersect:=(A,B)->select(member,A,B):
Note that member(x,S) is a Boolean function of two arguments, an expres-
sion x and a set S. In the above construct x runs through all operands of A,
while S is supplied as the optional third argument of select. This function
is slightly more exible than intersect: explore its behaviour.
Visible points
We provide a geometrical interpretation of the concept of relative primality,
introduced in section 2.4. A point on the plane whose coordinates are
integers will be called an integer point. We denote by Z2 the collection of
all integer points. An integer point (x; y ) is visible from the origin if the
segment connecting (x; y ) to (0; 0) does not contain any integer point beside
the endpoints ( gure 6.5).
The following result relates the geometrical and the arithmetical char-
acterizations of visible points.
Theorem 6 A point (x; y ) of Z2 is visible from the origin if and only if x
and y are relatively prime.

If x and y have a common divisor d > 1, then x = dx0 and y = dy 0 for


some integers x0 and y 0 , and since jx0 j < jxj and jy 0 j < jy j, the point (x0 ; y 0 )
6.3. FUNCTIONS ACTING ON OPERANDS OF EXPRESSIONS 123

d t d t d t

d t d d t d
(2,3)
(4,2)
d t d td t

d d d

d d
 (2,1) d

d  d t t t
x
(0,0)
d d d d d d

Figure 6.5: Visible and invisible points from the origin (0; 0) of Z2, repre-
sented by circles and solid circles, respectively. The point (2; 3) is visible,
while the point (4; 2) is not, since its view is obstructed by (2; 1).

obstructs the view of (x; y ) from the origin (think about it). This proves
the `if' bit of the theorem.
To prove the `only if' implication, we assume that x and y are coprime.
If jxj or jy j is equal to 1, then (x; y ) is clearly visible (draw a picture!),
so we shall assume that jxj; jy j > 1. We proceed by contradiction, and
assume that (x; y ) is not visible. Then there exists a point (x0 ; y 0 ) lying
between (x; y ) and the origin, which implies that xy 0 = yx0 . If x and x0
were coprime, then from the fundamental theorem of arithmetic, we would
conclude that x divides y (why?), contrary to the assumption that x and y
are coprime. So the greatest common divisor d of x and x0 is greater than
1, and we write x = ad, x0 = bd. Now, a and b are coprime, and moreover
a > 1, since 1  jx0 j < jxj. So a is also a proper divisor of y , and therefore
x and y are not coprime, a contradiction.

We wish to construct the (in)visible points contained within the square


region 0  x; y;  n, where n is an integer. We shall represent an integer
point as a two-element Maple list [x,y]. We begin by constructing the
Boolean characteristic function of the visible points
> chi:=z->evalb(igcd(op(1,z),op(2,z))=1):
Next we construct the set of all integer points in a suitably large square
region
> n:=50:
> IntPts:=fseq(seq([x,y],y=0..n),x=0..n)g:
The visible points are extracted from the above set using select
> VisPts:=select(chi,IntPts):
Note that VisPts is also a set, because select retains the data type of the
124 CHAPTER 6. STRUCTURE OF EXPRESSIONS

target expression. The invisible points are the di erence between the above
two sets
> InvisPts:=IntPts minus VisPts:
To plot (in)visible points, we must rst convert the corresponding data set
into a list.
> plot([op(VisPts)],style=POINT,scaling=`constrained`);

50

40

30

20

10

0 10 20 30 40 50

Considering horizontal and vertical lines, we see that the density of visible
points is maximal whenever the corresponding coordinate is a prime num-
ber, and minimal when it is an integer with a large number of divisors, e.g.,
30. (A more accurate formulation of this phenomenon requires knowledge
of Euler's -function.)
To count visible points, we use nops
> nops(VisPts);
1549
Since our region contains 512 = 2601 integer points, we see that approx-
imately 60% of them are visible from the origin. We shall return to the
question of the density of visible points in section 8.4, after having devel-
oped a more e ective method for counting such points.
6.3. FUNCTIONS ACTING ON OPERANDS OF EXPRESSIONS 125

Exercises
Exercise 6.4. Each expression E on the left is transformed into the ex-
pression on the right by map(f,E), for a suitable function f. Construct
such user-de ned function f in each case.
E map(f; E)

(a) [0; 1; 2; 3] [100; 101; 102; 103]


(b) a+b+c+d 1=a + 1=b + 1=c + 1=d
(c) f 20; 10; 10; 30; 20g f10; 20; 30g
(d) [0; 1; 1; 1; 0; 1; 0; 1] [1; 0; 0; 0; 1; 0; 1; 0]
(e) [a + b; c + d; e + f ] [a; b; c; d; e; f ]
(f ) [a + b; c + d; e + f ] [ab; cd; ef ]
(g ) [a3 ; b4 ; a7 ] [a=(3 + a); b=(4 + b); a=(7 + a)]
(h) [ [ a ]; [ [ b ] ]; [ [ [ c ] ] ]; [ [ [ [ d ] ] ] ] ] [ a; b; [ c ]; [ [ d ] ] ]
(i) [ [ a ]; [ d; e; f ]; [ g; h; i; j ]; [ b; c ] ] [ 1; 3; 4; 2 ]
(j ) [ [ a ]; [ b; c ]; [ d; e; f; g ]; [ h; i; j ] ] [ a; c; g; j ]

Exercise 6.5. The following function generates the list of the prime di-
visors of an integer n > 1.
> PrimeDiv:=n->[seq(expand(op(1,x)),x=ifactor(n))]:
> PrimeDiv(18800);
[2; 5; 47]
However, this function does not produce the desired answer for all values
of n. Characterize the set of integers n for which it does.
Exercise 6.6. A Maple list L contains numerical data, representing the
elements of a sequence.
(a) Plot the elements of L.
(b) Determine the number of negative elements of L.
(c) Let a1 ; : : : ; ak be the distinct elements of L, ordered arbitrarily. For
every i = 1; 2; : : : ; k , let ni be the frequency of occurrence of ai , i.e., the
number of times ai appears in L. Construct a function freq(L) which re-
turns the frequency of each distinct element of L, with the following format
[ [a1 ; n1 ]; [a2 ; n2 ]; : : : ; [ak ; nk ] ]:
Chapter 7

Polynomials and rational


functions
Polynomials and rational functions are Maple's favourite data types. In
this chapter we look at their arithmetical properties, which resemble those
of integers and rationals, respectively.

7.1 Polynomials

A polynomial is an object such as x3 3x 1, consisting of integers combined


with copies of an indeterminate x, raised to various integral powers. More
formally, let a0 ; a1 ; : : : ; an 1 ; an be n + 1 elements of a set K , equipped
with sum, subtraction, and multiplication (K is a ring or a eld), which
we will assume to be one of Z; Q; R , or C . A polynomial over K in the
indeterminate x with coeÆcients a0 ; : : : ; an is an expression
p = a0 x0 + a1 x1 + a2 x2 +    + an xn
1
1
+ an xn ak 2 K:
The set of all polynomials over K in the indeterminate x will be denoted
by K [x]. The integer n is the degree of p (denoted by deg(p)), and an is the
leading coeÆcient. The term x0 associated with the constant coeÆcient a0
is usually omitted, and so is the exponent 1 in x1 : p = a0 + a1 x + a2 x2 +   .
Example 7.1. The polynomial p = 3 x2 + 2 x3 is an element of Z[x].
Its coeÆcients are
a0 = 3; a1 = 0; a2 = 1; a3 = 2:
The degree of p is 3, and its leading coeÆcient is 2. Maple knows this
> p:=3-x^2+2*x^3;
p := 3 x2 + 2x3
127
128 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
> degree(%),lcoeff(%);
3; 2
Note that for the notion of degree to be well-de ned, we have tacitly
required that an be nonzero, if n is positive. (It would not make much sense
to say, for instance, that the polynomial 1 + 3 x + 0 x29 is a polynomial of
degree 29, with leading coeÆcient zero!)
The polynomials of degree 0 in K [x], given by p = a0 x0 , can be naturally
associated with the element a0 of K (even though a0 and a0 x0 are not quite
the same thing, as we shall see). Then an element of K can be thought of
as an element of K [x], and we have the inclusion K  K [x]. Moreover, if
K  L, then K [x]  L[x], because every polynomial with coeÆcients in K
is also a polynomial with coeÆcients in L. So, for instance, the chain of
inclusions (5.12) implies the associated chain of inclusions for polynomials

Z[x]  Q [x]  R[x]  C [x]:


Example 7.2. Examples of polynomials.

p deg(p) a0 a1 a2 a3 a4 K [x]
x4 4 0 0 0 0 1 Z[x]
3 x2 + 2x3 3 3 0 1 2 Z[x]
21=5 0 21=5 Q [x]
(x2 + 6)=3 2 2 0 1=3 Q [x]
p 2 p
5x x 2 0 1 5 R[x]
x3 i x=2 3 0 i=2 0 1 C [x]

7.2 Polynomial arithmetic

A polynomial is in the rst instance an arithmetical object, not a function of


the indeterminate. We are not interested in substituting any speci c value
for x. (Accordingly, we tend to de ne a polynomial as a Maple expression,
rather than a Maple function.) The role of the indeterminate is merely that
of organizing the sequence of coeÆcients.
Arithmetically, polynomials behave much like integers. The elements of
K [x] can be summed, subtracted, and multiplied unrestrictedly, and this
results from the fact that the elements of K , as well as the indeterminate
x, enjoy that same property.
7.2. POLYNOMIAL ARITHMETIC 129

Addition and subtraction


The coeÆcient of the term xk of the sum (di erence) of two polynomials
is given by the sum (di erence) of the corresponding coeÆcients of the
summands.
We begin with an example. Let p = 5 + x and q = x + x2 . We write
all coeÆcients explicitly, matching degrees
p = 5 + 1 x + 0 x2 q = 0 1 x + 1 x2 :
Then
p + q = ( 5 + 0) + (1 1)x + (0 + 1)x2 = 5 + x2
p q = ( 5 0) + (1 ( 1))x + (0 1)x2 = 5 + 2x x2 :
> p:=-5+x:
> q:=-x+x^2:
> p+q,p-q;
5 + x2 ; 5 + 2x x2
As for integers, the sum and subtraction are worked out automatically by
Maple. Note that sum and subtraction may lower the degree, by cancelling
out the leading coeÆcient
> p:=2+2*x^5:
> q:=x^3-2*x^5:
> degree(p),degree(q),degree(p+q),degree(p-q);
5; 5; 3; 5
In this example, a polynomial of degree 3 resulted from the sum of two
polynomials of degree 5. It should be clear that sum or subtraction cannot
increase the degree; so the rule relating the degree of the summands to that
of the sum is given by
 
deg p  q  max deg(p); deg(q) :
To de ne the operations of sum and subtraction in the general case, it
is convenient to regard a polynomial as an in nite sum
1
X
p= ai xi (7.1)
i=0
where only nitely many coeÆcients ai are allowed to be nonzero. Then
the sum (7.1) only `looks' in nite, but is actually nite. With this de-
vice the sum/subtraction of two polynomials can be written without being
concerned about their degrees
1
X 1
X 1
X
pq = ai xi  bi xi = (ai  bi ) xi :
i=0 i=0 i=0
130 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
We see that the coeÆcients of the sum (di erence) of p and q are the
sum (di erence) of the respective coeÆcients. Is p  q as de ned above a
polynomial? Yes, because the rightmost sum also has nitely many nonzero
coeÆcients, as easily veri ed (do it!).
Multiplication
We begin with an example. Let p = 1 2 x + x2 and q = 3 + 5 x2 x3 .
Then, writing all coeÆcients explicitly, we have
p  q = (1 2 x + 1 x2 )  (3 + 0 x + 5 x2 1 x3 )
= (1  3) + ( 2  3 + 1  0) x + (1  3 + ( 2)  0 + 1  5) x2
+ (1  ( 1) + ( 2)  5 + 1  0) x3
+ (( 2)  ( 1) + 1  5) x4 + (1  ( 1)) x5
= 3 6 x + 8 x2 11 x3 + 7 x4 x5 :
To nd the coeÆcient of xk in the product of two polynomials, we multiply
the coeÆcient of xj in one polynomial with the coeÆcient of xk j in the
other, and then add all these products, for j = 0; 1; : : : ; k .
> p:=1-2*x+x^2:
> q:=3+5*x^2-x^3:
> p*q;
(1 2 x + x2 ) (3 + 5 x2 x3 )
> expand(%);
3 + 8 x2 11 x3 6 x + 7 x4 x5
Contrary to what happens for numbers, Maple does not expand the product
of polynomials automatically. There is a good reason for this, as we shall
see. To force expansion, one must use the function expand, which multiplies
out the factors, and then carries out standard simpli cations. (Note that
Maple does not necessarily represent the polynomial in ascending powers of
the indeterminate.) The only instance in which Maple expands a product
automatically is when one of the operands has degree zero.
> 9*(x+2);
9x + 18
The formula for polynomial multiplication is a bit more complicated
than that for addition. Using again the representation of polynomials as
in nite sums with nitely many nonzero coeÆcients, we let
1
X 1
X 1
X
pq = ai xi  bi xi = ci xi
i=0 i=0 i=0
where (see exercises)
i
X X
ci = aj bi j = aj bk ; i = 0; 1; : : : : (7.2)
j =0 j +k=i
7.2. POLYNOMIAL ARITHMETIC 131

The degree of the product of two polynomials is equal to the sum of the
degrees of the operands

deg p  q = deg(p) + deg(q ):

Division
Like for integers, the ratio of two polynomials may or may not be a poly-
nomial. In K [x] | which is structurally identical to Z | division cannot
always be carried out, and one needs to introduce the corresponding notion
of divisibility.
Given two polynomials p and q in K [x], we say that p divides q if there
exists a polynomial h in K [x] such that p h = q . As for integers, we write
pjq to denote divisibility.
For instance, let p = 1 x and q = 1 + x2 . Then p divides q in Z[x],
because there exists the polynomial h = 1 x such that ph = q .
> p:=1-x:
> q:=-1+x^2:
> q/p;
1 + x2
1 x

> simplify(%);
x 1
Again, Maple refuses to carry out the simpli cation automatically, and we
have to use the function simplify for this purpose.
A greatest common divisor of two polynomials is a polynomial of highest
degree dividing both. A least common multiple of two polynomials is a
polynomial of smallest degree divisible by both. They are unique up to a
constant factor.
Example 7.3. The divisors of a polynomial come in pairs. Indeed, if p
divides q , then also q=p divides q , and vice versa. The argument is identical
to that given in chapter 2 for the integers. Thus, in the above example,
both p = 1 x and q=p = 1 x divide q . As for the integers, the number
of divisors of a polynomial p is even, except when p is a square of another
polynomial.
The analogy between polynomials and integers can be carried out fur-
ther.
Theorem 7 If f and g are polynomials over Q , R, or C , and g is nonzero,
then one can nd unique polynomials q and r such that
f = gq +r (7.3)
where r has smaller degree than g .
132 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
The polynomials q and r are the quotient and the remainder, respec-
tively, on dividing f by g . (Compare with the analogous construction
given in equation (2.10).) Note that the above theorem does not apply to
polynomials in Z[x]. To see why, let us consider the case f (x) = x2 1 and
g(x) = 2x 2. Then g divides f in Q [x], but not in Z[x]
 
1 1
x 2
1 = (2x 2) x+ :
2 2
In Z[x], the equation (7.3) gives q (x) = 0 and r(x) = g (x), with the de-
gree of r(x) equal to that of g (x). It turns out that Theorem 7 can be
extended to Z[x], provided that we consider only monic polynomials, that
is, polynomials with leading coeÆcient equal to 1.
Quotient and remainder may be computed using the long division algo-
rithm from elementary algebra. The working for the case f = x5 1 and
g = x2 x 1 is displayed below

x5 1 x2 x 1
x5 x4 x3
x4 + x3 x3 + x2 + 2 x + 3
x4 x3 x2
2 x3 + x2
2 x3 2 x2 2 x
3 x2 2 x 1
3 x2 3 x 3
5x+2

One nds that q = x3 + x2 +2 x +3 and r = 5 x +2. Equation (7.3) becomes


x5 1 = (x2 x 1)(x3 + x2 + 2 x + 3) + 5 x + 2:
What are the `prime' polynomials? A polynomial over K [x] is said to
be irreducible if it cannot be expressed as the product of two polynomials
of K [x] of smaller degree. Thus, the polynomial p = x2 x 2 of degree
2 is not irreducible in Q [x], because p = (x 2)(x + 1) is the product of
two polynomials in Q [x] of degree 1. For this de nition to work, we have
to agree that the polynomials of degree 0 are not considered irreducible,
much in the same way as the integer 1 is not considered prime.
Theorem 8 (the fundamental theorem of polynomial arithmetic). Every
polynomial over Q , R, or C can be expressed as a product of irreducibles,
and this factorization is unique up to constant factors and the order of the
factors.
7.2. POLYNOMIAL ARITHMETIC 133

The formulation of this theorem is virtually identical to that of the


fundamental theorem of arithmetic. The only extra condition is that con-
stant factors are to be ignored when considering the question of uniqueness
of the decomposition into irreducibles, in accordance with our de nition
of irreducibility. To illustrate this point, let us consider the polynomial
2 + 2x = 2(1 + x). If we do not ignore the constant factor 2, which is a
polynomial of degree zero, then we would conclude that this polynomial
has at least two distinct representations into irreducibles.
Maple has functions for divisibility of polynomials over Q (and Z) which
mimic closely the corresponding functions for integers.

DIVISIBILITY FUNCTIONS
FOR INTEGERS AND POLYNOMIALS OVER Q
integers polynomials

iquo(a,b) quo(p,q,x)
irem(a,b) rem(p,q,x)
igcd(a,b) gcd(p,q)
ilcm(a,b) lcm(p,q)
ifactor(a) factor(p)

Example 7.4. Consider the following factorizations


> ifactor(6),factor(1-x^3);
(2)(3); (x 1)(x2 + x + 1)
In the same way that 2 and 3 are the prime factors of 6 in Z, so 1 x and
1 + x + x2 are the irreducible factors of 1 x3 in Q (x).
> ifactor(6),factor(6);
(2)(3); 6
Maple factors the integer 6 in Z, but it does not factor the degree zero
polynomial 6 = 6 x0 in Q [x], conforming with the stipulation that such
polynomials are excluded from the factorization process (cf. remark before
Theorem 8). This example shows the extent to which the integer n and the
polynomial n = n x0 of degree 0 cannot be identi ed.
Example 7.5. Quotient and remainder.
> f:=x^4+x+1:
> g:=x^2-1:
> quo(f,g,x);
x2 + 1
> rem(f,g,x);
x+2
134 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
> evalb(expand((g*%%+%)-f)=0);
true
The last statement veri es the equality (7.3).
Example 7.6. Divisibility and remainder. As we did for the integers,
we can use rem to test divisibility of polynomials. The following function
returns true if q divides p in Q [x], and false otherwise.
> dvd:=(p,q,x)->evalb(rem(p,q,x)=0):

Sequences of polynomials
A sequence g0 ; g1 ; g2 ; : : : of polynomials in K [x] is a function that associates
to every natural number t an element of K [x]
g:N ! K [x] g := t 7! gt :
Note that in this context g is a function of t, not a function of x. For
instance, if we let
g:N ! Z[x] g := t 7! x2 tx + t 1
we obtain a sequence of polynomials over Z, all of degree 2
x2 1; x2 x; x2 2x + 1; : : :

> g:=t->x^2-t*x+t-1:
> seq(g(t),t=0..5);

x2 1; x2 x; x2 2 x + 1; x2 3 x + 2; x2 4 x + 3; x2 5x +4
In the above example the variable x is not passed to the function g as an
argument. We say that x is a global variable, meaning that its value can be
modi ed from outside the function.
> x:=-1:
> seq(g(t),t=0..5);
0; 2; 4; 6; 8; 10
Global variables can lead to unpredictable results and should be used spar-
ingly.
Sequences of polynomials can be de ned recursively, in a manner anal-
ogous to sequences of numbers. In the simplest instances, a recursive se-
quence is de ned by the initial condition g0 , which is a given polynomial
f 2 K [x], and by a rule that de nes the element gt+1 of the sequence as
7.2. POLYNOMIAL ARITHMETIC 135

a given function of gt . Such function is arbitrary, and in particular it may


involve other polynomials in K [x].
g0 = f gt+1 = F (gt ); t  0:
For instance, let K = Z, and let
g0 = 1 + x gt+1 = x2  gt2 1; t  0:
Then
g1 = x2 g02 1 = x2 (x + 1)2 1 = x4 + 2x3 + x 1;
g2 = x2 g12 1 = x2 (x2 (x + 1)2 1)2 1
= x10 + 4 x9 + 6 x8 x6 + 4 x7 4 x5 2 x4 + x2 1;
..
.

Example 7.7. Polynomials as sequences of coeÆcients. For a polynomial,


the role of the indeterminate is simply that of organizing a nite sequence of
coeÆcients. We can dispose of the indeterminate altogether and represent
polynomials as sequences of elements of the underlying set K . Thus, the
polynomial p = 3 x2 +2x3 in Z[x] can be represented as the nite sequence
of integers p = (a0 ; a1 ; a2 ; a3 ) = (3; 0; 1; 2). Better still, we could regard p
as an in nite sequence of elements of Z, with only a nite number of them
being di erent from zero: p = (3; 0; 1; 2; 0; 0; : : :). With this device, the
arithmetic of polynomials is described in very elegant terms. For instance,
if p = (a0 ; a1 ; : : :) and q = (b0 ; b1 ; : : :) are polynomials over K , then p + q =
(a0 + b0 ; a1 + b1 ; : : :). Furthermore, the elements of K are identi ed with
the sequences where only the rst term is nonzero
p2K () p = (a; 0; 0; 0; : : :):
Polynomials in several indeterminates 
We have considered polynomials whose coeÆcients are numbers. However,
all that is required from the coeÆcients is the possibility of performing the
arithmetical operations of sum, subtraction, and multiplication. But these
properties are also enjoyed by polynomials, so it makes sense to consider
polynomials whose coeÆcients are themselves polynomials.
For illustration, let us consider the expression
p = (c3 + 2 c2 + c 1) + x (c2 + 2 c + 1) + x3 (3 c 1) + x4 :
This is a polynomial of degree 4 in the indeterminate x: p = a0 + a1 x +
a2 x2 + a3 x3 + a4 x4 . Its coeÆcients ak are polynomials in the indeterminate
c
a0 = c3 + 2 c2 + c 1; a1 = c2 + 2 c + 1; a2 = 0; a3 = 3 c 1; a4 = 1:
136 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
Thus, the coeÆcients of p belong to Z[c], so that p belongs to Z[c][x]. It is
customary to denote the latter set by Z[c; x], which underlines the fact that
the indeterminates x and c have equal status. This means that we could
equally regard this polynomial as a polynomial in the indeterminate c
p(c) = ( 1 + x x3 + x4 ) + c (1 + 2 x + 3 x3 ) + c2 (x + 2) + c3 :
This time p(c) = b0 + b1 c + b2 c2 + b3 c3 is a polynomial of degree 3, with
coeÆcients in Z[x]
b0 = 1 + x x3 + x4 ; b1 = 1 + 2 x + 3 x3 ; b2 = x + 2; b3 = 1:
(This example should make it clear that Z[x; c] = Z[c; x]; think about it.)
The Maple intrinsic function degree accepts an optional second argument
specifying the indeterminate with respect to which the degree is to be eval-
uated
> p:=(c^3+2*c^2+c-1) + x*(c^2+2*c+1)+ x^3*(3*c-1)+x^4:
> degree(p,x),degree(p,c);
4; 3

Exercises
Exercise 7.1. Prove the formula (7.2) for the coeÆcients of the product
of two polynomials.
Exercise 7.2. Prove that the degree of the product of two polynomials
is equal to the sum of the degrees of the operands.
Exercise 7.3. Show that x + x + x + x + 1 and x + x + 1 are relatively
4 3 2 2

prime.
Exercise 7.4. List all common divisors of x6 x5 2x4 + x3 + x2 +2x 2
and x x x + 1 in Z[x].
5 3 2

Exercise 7.5. Let


f = x6 x 1 g = x3 + x + 1:
Let q and r be the quotient and remainder, respectively, of the division of
f by g. Verify that
f r
= q+ :
g g
Exercise 7.6. Consider the recursive sequence of polynomials in Z[x]
g0 = x gt+1 = 1 + x  gt ; t  0:
Determine the smallest value of t for which gt is reducible.
7.2. POLYNOMIAL ARITHMETIC 137

Exercise 7.7. Consider the sequence of polynomials over Z


pn (x) = x2 n 1
+1 n  1:
Let qn (x) be the quotient of the division of pn (x) by x + 1. Determine the
sequence qn (x), n  1.

Exercise 7.8. Consider the sequence of polynomials over Z


cn (x) = xn 1 n  1:
The purpose of this exercise is to study how the elements of this sequence
factor into the product of irreducible polynomials.
(a) Construct a Maple function c(n), whose value is cn (x), in factored
form. Hence factor cn (x) for n = 6; 9; 12; 13. In each case, count the
number of irreducible factors, and then verify that such number is also
the value of the Maple function nops applied to the factored expression of
cn (x). (This does not work when n = 1, though | why?)
(b) Let n be a positive integer, and let In be the number of irreducible
factors of cn (x). So we have the sequence of positive integers
I1 ; I2 ; I3 ; : : : n  1:
Using nops, construct a function called nf(n) whose value is In for n  2
(this function will give the wrong answer for n = 1). Test it. Hence compute
I83 and I84 .
(c) Plot the rst 30 elements of the sequence n 7! In , including the correct
entry for n = 1. Observe the very irregular behaviour of this sequence.
(d) Let In be as above. There exists a close relationship between In and
the divisors of n. Discover what it is, and then express your ndings in the
form of a conjecture.

 Let f (x) be a polynomial. A number is a root of f (x)


Exercise 7.9 .
p p
if f ( ) = 0. Thus, 2 is a root of f (x) = x2 2, and so is 2.
For any positive integer n, we let
fn (x) = xn 1 n;k = e2ik=n ; k = 0; 1; : : : ; n 1:
Then n;k is a root of fn (x) for any choice of k , because
fn ( n 1 = e2ik 1 = 0:
n;k ) = n;k 1=1
Now let n = 15. The polynomial f15 (x) factors into the product of ir-
reducible polynomials, the largest of which has degree 8. Determine the
8 values of k corresponding to the roots of the latter. (You must do so
without performing oating-point calculations.)
138 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
7.3 Rational functions

The lack of closure of the integers under division led to the introduction of
the rational numbers. With polynomials there is a similar need of enlarging
the set K [x] in order to achieve closure with respect to division. Thus, the
ratio (x2 1)=(x 1) = x + 1 is a polynomial, because x 1 divides x2 1
> (x^2-1)/(x-1):%=simplify(%);
x2 1
= x+1
x 1
However, the ratio (x2 1)=(x 2) is not a polynomial, since x 2 does
not divide x2 1.
> simplify((x^2-1)/(x-2));
x2 1
x 2
In this case we speak of a rational function.
The rational functions over K in the indeterminate x | denoted by
K (x) | is the set of fractions whose numerator and denominator are ele-
ments of K [x], and the denominator is nonzero. This construction is analo-
gous to the construction of Q from Z. In particular, we have K [x]  K (x),
since every polynomial over K is also a rational function with denominator
1 = 1  x0 , and the latter is itself a polynomial over K . (This is due to the
fact that every eld K contains 1; see section 12.3.) So we have the chain
of inclusions
Q (x)  R(x)  C (x):
Note that we have not mentioned the set Z(x), since the latter is equal to
Q (x). (Why?)
Recall that Maple simpli es rational numbers in such a way that the
denominator is positive, and the numerator and denominator are relatively
prime. Maple does not simplify rational functions, unless the simpli cation
is obvious, that is, unless the quantity to be simpli ed is already factored.
The intrinsic function simplify represents a rational function over Q so
that numerator and denominator are relatively prime and their coeÆcients
are integer (so does the function normal).
> p:=(x-1)*(x-2)*(x-3):
> q:=(x-1)*(x+1):
> p/q;
(x 2)(x 3)
x+1
> p/expand(q);
(x 1)(x 2)(x 3)
x2 1
> simplify(%);
7.4. BASIC MANIPULATIONS 139

(x 2)(x 3)
x+1
Simpli cation is not always desirable. For instance, the rational function
x1000000 1
x 1
= x999999 + x999998 +  +x +1
which is de ned by two polynomials with four nonzero coeÆcients in all,
`simpli es' to a polynomial with one million nonzero coeÆcients!

7.4 Basic manipulations

We have already considered the functions expand and factor


> p:=(x-1)*(x^2+2*x+1):
> expand(p);
x3 + x 2 x 1
> factor(%);
(x 1)(x + 1)2
> op(%);
x 1; (x + 1)2
With expand, all products are distributed over sums, and like terms are
collected
(x + 2)(x + 3) ! x(x + 3) + 2(x + 3)
! x2 + 3x + 2x + 6
! x2 + 5x + 6
or
(x + 2)(x + 3) ! x(x + 2) + 3(x + 2)
! x2 + 2x + 3x + 6
! x2 + 5x + 6
You can ask Maple to leave sub-expressions intact, by specifying a sub-
expression as an optional second argument
> p:=(x+2)*(x+3)^2:
> expand(p,x+3);
(x + 3)2 x + 2 (x + 3)2
> expand(p,x+2);
(x + 2) x2 + 6 (x + 2) x + 9x + 18
Note that the term 9(x + 2) is automatically expanded.
The function expand also distributes positive integer powers over sums
> (x+1)^3;
140 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
(x + 1)3
> expand(%);
x3 + 3x2 + 3x + 1
but negative powers are left untouched
> g:=(x+1)^(-2);
1
g :=
(x + 1)2
> expand(g);
1
(x + 1)2
In this case, the expansion of the denominator must be carried out explicitly
> 1/expand(denom(g));
1
x + 2x + 1
2

The following example illustrates the di erent behaviour of expand on the


numerator and the denominator of a rational expression
> x*(x+1)/(x-1)^2;
x (x + 1)
(x 1)2
> expand(%);
x2 x
+
(x 1)2 (x 1)2
The procedure simplify provides | among other things | a standard
simpli cation of rational functions over Q . It transforms a rational function
in the form
numerator
denominator
with numerator and denominator relatively prime polynomials with integer
coeÆcients.
> x*(x+2/3*x^3)/(x+1/7);
 3

x x + 2 3x
x + 17
> simplify(%); 
7 x2 3 + 2 x2
3 7x+1
In the above expression, all fractional coeÆcients have been cleared.
> x+1/(x^2+1/(x^3+1/x^4));
7.4. BASIC MANIPULATIONS 141

1
x+
1
x2 +
1
x3 +
x4
> simplify(%),factor(%);

x10 + x3 + x5 + x7 + 1 x10 + x3 + x5 + x7 + 1
; 2 2
x (x + 1 + x )
2 7 2 x (x + x + 1) (x5 x4 + x2 x + 1)
Here simplify has produced a partially factored denominator. By contrast,
the function factor, when applied to a rational expression, provides a
simpli ed and fully factored form, and may be used as an alternative to
simplify, keeping in mind that it is more expensive to evaluate. For
simpli cation of rational expressions, see also ?normal.
A trick of the trade
We consider the problem of proving the following identity with Maple
1 (1 + x)3 + 1
(1 + x)2 + = :
1+x 1+x
> rf:=(1+x)^2+1/(1+x):
The procedure simplify does not do what we want
> simplify(rf);
2 + 3x + 3x2 + x3
1+x
and factorization does not help, either
> factor(%);
(x + 2)(x2 + x + 1)
1+x
The idea is to perform a substitution in order to `freeze' the subexpression
1 + x.
> subs(1+x=y,rf);
1
y2 +
y
> simplify(%);
y3 + 1
y
> subs(y=1+x,%);
(1 + x)3 + 1
1+x
142 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
7.5 Partial fractions decomposition

The decomposition into partial fractions is an important representation of
a rational function. We consider an example.
> (x+1)/(x^4-2*x^3+x^2-2*x);
x+1
(7.4)
x4
2x3 + x2 2x
The conversion to partial fractions is done by the many-purpose intrinsic
function convert (check the online documentation)
> convert(%,'parfrac',x);
11 3 1 1 3+x
+ +
2 x 10 x 2 5 x2 + 1
How does this decomposition work? The denominator of the rational func-
tion (7.4) factors into the product of three irreducible polynomials
x+1 x+1
= :
x4 2x3 + x2 2x x(x 2)(x2 + 1)
The right-hand side is then converted to the form
q1 q q
+ 2 + 3
x x 2 x2 + 1
where
1 3 3 x
q1 = q2 = q3 = + :
2 10 5 5
The three polynomials qk are polynomials over Q with degree lower than
that of the corresponding denominator. The following theorem describes
the general situation.
Theorem 9 Let f=g be a rational function over Q , whose numerator is of
lower degree than the denominator. Let
g = pe11  pe22    perr
be the factorization of the denominator into irreducibles. Then there exist
polynomials q1 ; : : : qr , with deg(qk ) < deg(pk ), for k = 1; : : : ; r, such that
f q q
g
= t11 + t22 +
p1 p2
   + pqtrr
r

and tk  ek ; k = 1; : : : ; r.
A common use of the decomposition into partial fractions is to integrate
rational functions.
7.5. PARTIAL FRACTIONS DECOMPOSITION 143

Exercises
Exercise 7.10. Consider the polynomial (2x3 x)(x2 x 1). Using
Maple, transform this polynomial into:

(a) 2 x5 2 x4 3 x3 + x2 + x
(b) x (2x2 1)(x2 x 1)
(c) x3 (2 x2 1) x2 (2 x2 1) x (2 x2 1)
 
(d) 2 x3 x2 x 1 x x2 x 1

(e) x 2 x4 2 x3 3 x2 + x + 1 :

Exercise 7.11. Consider the rational function


x3 3x + 2
:
x3 2x2 x + 2
Using Maple, transform this rational function into:

(a) (x 1)2 (x + 2)
x3
2 x2 x + 2

(b) x3 3x+2
(x + 1) (x 1) (x 2)

(c) (x 1)2 x + 2 (x 1)2


(x 2) x2 x + 2

(d) x2 + x 2
x2 x 2
(e) (x + 2) (x 1)
(x + 1) (x 2)

(f ) x2 x 2
(x + 1) (x 2) + (x + 1) (x 2) (x + 1) (x 2) :

Exercise 7.12.

(a) Using Maple, show that


(x + 1)1000 1 1 x
+ = + 1:
(x + 1)1000 (x + 1)999 (x + 1)1000
WARNING: make sure you do not expand the binomials!
144 CHAPTER 7. POLYNOMIALS AND RATIONAL FUNCTIONS
(b) Using Maple, transform
1
x2 2x + 1 +
x2 2x + 1
into
1 + (x 1)4
(x 1)2
and vice versa. (Hint: you may need asubs.)

Exercise 7.13.

(a) Show that x4 + x3 + x2 + x + 1 and x2 + x + 1 are relatively prime.


(b) List all common divisors of x6 x5 2x4 + x3 + x2 + 2x 2 and
x5 x3 x2 + 1 in Z[x].
(c) Let
f (x) = x6 x 1 g(x) = x3 + x + 1:
Let q (x) and r(x) be the quotient and remainder, respectively, of the divi-
sion of f (x) by g (x). Verify that
f (x) r(x)
= q (x) + :
g(x) g(x)
Exercise 7.14.
(a) Consider the recursive sequence of polynomials in Z[x]
g0 (x) = x gt+1 (x) = 1 + x  gt (x); t  0:
Determine the smallest value of t for which gt (x) is reducible.
(b) Consider the recursive sequence of rational functions over Q
1
r0 (x) = x3 rt+1 (x) = x + ; t  0:
rt (x)
Show that the numerator of r2 (x) is divisible by x2 x + 1.

Exercise 7.15. Let h(x) = f (x)=g (x) be a rational function and let r(x)
be the remainder of division of f (x) by g (x). We de ne

fh(x)g = gr((xx)) :
Consider the function
8n o
< 1
h(x) h(x) 6= 0
 (h(x)) =
:
0 otherwise.
7.5. PARTIAL FRACTIONS DECOMPOSITION 145

Show that the elements of the following recursive sequence of rational func-
tions over Q
x3 + x + 1
h0 (x) = ht+1 (x) =  (ht (x)); t0
x5 + x + 1
becomes eventually zero.
Chapter 8

Finite sums and products


In this chapter, we develop the tools for summing and multiplying a large
(albeit nite) number of elements of a sequence. In this way, we shall
construct new sequences from old ones.

8.1 Basics

We consider a sequence of elements of a set A


a0 ; a1 ; a2 ; : : : ak 2 A: (8.1)
All we require from A is that its elements can be added and multiplied
together, e.g., A = N ; Z; Q [x]; : : : etc. Then we form sums and products of
the elements of the sequence (8.1)
X
n

Sn = a0 + a1 + a2 +  +a n = ak n  0; (8.2)
k=0

Y
n

Pn = a0  a1  a2  a n = ak n  0: (8.3)
k=0

It should be clear that, for any given sequence ak , the quantities Sn and
Pn are functions of n, and hence they are new sequences
n 0 1 2 3 
an a0 a1 a2 a3 
Sn a0 a0 + a1 a0 + a1 + a2 a0 + a1 + a2 + a3 
Pn a0 a0  a1 a0  a1  a2 a0  a1  a2  a3 
We begin with some examples.

147
148 CHAPTER 8. FINITE SUMS AND PRODUCTS

Example 8.1. A = Z, an = 1, n  0.

n 0 1 2 3 4 5 
an 1 1 1 1 1 1 
Sn 1 2 3 4 5 6 
Pn 1 1 1 1 1 1 
We have Sn = n + 1, and Pn = 1.

Example 8.2. A = Z, an = n, n  1.

n 1 2 3 4 5 
an 1 2 3 4 5 
Sn 1 3 6 10 15 
Pn 1 2 6 24 120 
We have
n(n + 1)
Sn = Pn = n! : (8.4)
2
The leftmost formula is the sum of the arithmetic progression.

Example 8.3. A = Z, an = ( 1)n , n  0.

n 0 1 2 3 4 5 
an 1 1 1 1 1 1 
Sn 1 0 1 0 1 0 
Pn 1 1 1 1 1 1 
We have
1 + ( 1)n
Sn = Pn = ( 1)b(n+1)=2c
2
where b  c is the oor function.

Example 8.4. A = Z[x], an = xn , n  0.

n 0 1 2 3 :::
an 1 x x2 x3 
Sn 1 1+x 1 + x + x2 1 + x + x2 + x3 
Pn 1 x x3 x6 
8.2. SUMS AND PRODUCTS WITH MAPLE 149

We have
xn+1 1
Sn = Pn = x n(n+1)=2 : (8.5)
x 1
In the leftmost expression we can substitute for x any numerical value
x 6= 1, to obtain the formula for the sum of the geometric progression.
Example 8.5. Summing characteristic functions. Let A be a subset
of N , and let A be the characteristic function of A in N (cf. (3.14)). We
wish to count the elements of A that are not greater than a given natural
number n. Let this number be A(n). Because A (k ) is 0 if k 62 A, and 1 if
k 2 A, we have
X
n

A(n) = A (k ):
k=0

For instance, if A is the set of primes, then A(n) is the number of primes
not exceeding n.

8.2 Sums and products with Maple

Whenever the elements of a sequence can be represented explicitly by a


Maple expression, then any nite sum or product of these elements can be
performed using the standard library functions add and mul. Sums and
products of the type (8.2) and (8.3), respectively, are represented as
> add(expr, k=m..n);
> mul(expr, k=m..n);
where the rst argument expr is any Maple expression representing the
coeÆcients ak , and the summation (multiplication) index k ranges between
the numerical values m and n (usually integer). The syntax of add and mul
is similar to that of seq. In particular, the range of summation (multipli-
cation) can be replaced by any expression e
> add(expr, k=e);
> mul(expr, k=e);
in which case the sum (product) is performed evaluating a at each operand
of e (see section 6.3).
Example 8.6. Compute the sum of the cubes of the rst 100 positive
integers. This is the sum of the rst 100 terms of the sequence ak = k 3 ; k =
1; 2; : : :
100
X
ak ak = k 3 :
k=1

We rst construct a user-de ned function representing the summands ak ,


and then perform the sum using such function
> cube:=k->k^3:
> add(cube(k), k=1..100);
150 CHAPTER 8. FINITE SUMS AND PRODUCTS

25502500
Alternatively, the expression for the summands could have been stored in
a variable, or used directly as the rst argument of the function add
> a:=k^3:
> add(a,k=1..100),add(k^3, k=1..100);
25502500; 25502500
We shall, however, favour the explicit representation of the summands as
values of a function, because this construct helps clarify the structure of
the summation process.
Example 8.7. Compute the product of the rst 20 prime numbers. The
elements of the sequence of primes are available through the standard li-
brary function ithprime
> mul(ithprime(s),s=1..20);
557940830126698960967415390
Example 8.8. Verify that 33 factorial is actually the product of the rst
33 positive integers
> evalb(mul(things,things=1..33)=33!);
true
In this example, the relevant sequence is just the identity sequence ak = k ,
for which we have not constructed a user-de ned function. The following
(rather pedantic) alternative solution underlines this point
> id:=x->x:
> mul(id(i),i=1..33)-33!;
0
Example 8.9. We construct the function 1 (n), which gives the number
of primes of the form 4k + 1 which are not greater than n. (This is a
specialization of the prime counting function  introduced in section 2.6.)
We rst construct the characteristic function of the set of such primes, and
then sum.
> chi:=k->if irem(k,4)=1 and isprime(k) then 1 else 0 fi:
> pi1:=n->add(chi(k),k=1..n):
> pi1(100);
11
Example 8.10. Consider the following sequence of elements of Z[x]
X
n

Sn = xk kx + 1 n  1:
k=1
8.2. SUMS AND PRODUCTS WITH MAPLE 151

We show that the polynomial S5 is irreducible.


> p:=k->x^k-k*x+1:
> S:=n->add(p(k),k=1..n):
> factor(S(5));

5 + x2 14 x + x3 + x4 + x5

Example 8.11. Partial factorizations. We consider the polynomial iden-


tities
11
X
xk = (x + 1) (x2 + 1) (x2 + x + 1) (1 x + x2 ) (x4 x2 + 1)
k=0

= (x2 + x + 1) (x3 + x9 + x6 + 1):

How can we achieve the rightmost representation (a partial factorization),


starting from the leftmost one (a full expansion)? We rst need a full
factorization
> p:=factor(add(x^k,k=0..11));

p := (x + 1) (x2 + 1) (x2 + x + 1) (1 x + x2 ) (x4 x2 + 1)

This is an expression of the `*' type, with 5 operands


> whattype(p),nops(p);

; 5
To achieve a partial factorization, we must assemble and multiply together
the relevant operands
> op(3,p)*expand(mul(op(k,p),k=[1,2,4,5]));

(x2 + x + 1) (x3 + x9 + x6 + 1)
The same construct is also possible with integers
> ifactor(30!);

(2)26 (3)14 (5)7 (7)4 (11)2 (13)2 (17) (19) (23) (29)

> op(1,")*op(nops("),")*expand(mul(op(k,"),k=2..nops(")-1));

136295711075535652265625 (2)26 (29)


(It is worth recalling that the order in which the factors are displayed is
context-dependent.)
152 CHAPTER 8. FINITE SUMS AND PRODUCTS

8.3 Symbolic evaluation of sums and

products

If the elements ak of a sequence are expressed as an explicit function of


k , can the associated sum Sn or product Pn be expressed as an explicit
function of n? This is clearly possible in some cases, e.g., for the sum of
the arithmetic and geometric progressions (see (8.4) and (8.5))
X
n
n (n + 1) X
n
xn+1 1
k = xk = ; x 6= 1: (8.6)
k=1
2 k=0
x 1

Such formulae allow us to compute the above sums for any given value of
n, with much less computational work than carrying out the sum explicitly
10 4
X 104 (104 + 1) 103 (103 + 1)
k = = 49505500: (8.7)
k=103
2 2

Note the structural analogy with the problem of constructing inde nite
integrals Z Z x
1
x dx = y dy = x2 :
0 2
Maple provides the standard library functions sum and product which
are designed to perform symbolic (i.e., inde nite) summations and prod-
ucts, rather than to explicitly add or multiply quantities. Their syntax
is the same as that of add and mul, except that the range of summation
(product) may now be symbolic, not just numerical. The function sum
will attempt to `discover' a formula for inde nite summation every time it
is called with a non-numerical range (the reader should be aware that this
process is time-consuming). If the range is numerical, sum and product will
give the same result as add and mul, respectively, except a lot more slowly.
So the use of these functions for de nite summations is to be avoided.
For instance, sum can nd the formula for the inde nite sum of the
arithmetic and geometric progressions (8.6)
> AS:=sum(k,k=1..n);
1 1 1
AS := (n + 1)2 n
2 2 2
> factor(%);
1
n (n + 1)
2
The function factor is legitimate here, because the value of the sum is a
polynomial in Q [n]. Now that we have a formula, we can compute the sum
(8.7) with substitutions
8.3. SYMBOLIC EVALUATION OF SUMS AND PRODUCTS 153

> subs(n=10^4,AS)-subs(n=10^3,AS);
49505500
The geometric sum is treated similarly
> GS:=sum(x^k,k=1..n);
x(n+1) 1
GS :=
x 1 x 1
> simplify(%);
x(n+1) 1
x 1
The reader is invited to compare the amount of computation involved
in evaluating the arithmetic sum for a large value of n, using add, sum with
a numeric argument, and substitution into the symbolic expression AS.
Let us consider another example. The terms of the sum
 
X
n
k2
Sn =
k=1
k

are given by an explicit function of k . Is there a simple formula for Sn this


time?
> bin:=k->binomial(k^2,k):
> S:=sum(bin(k),k=1..n):
> S;
X
n

binomial(k 2 ; k )
k=1

Maple cannot nd such a formula. This, of course, does not mean that
there isn't one, but only that the function sum cannot nd it. Substituting
an integer value for n in the expression S will cause the de nite summation
to be performed explicitly
> subs(n=4,S);
1911
However, since the evaluation of the inde nite sum failed in this case, the
use of add would be preferable.
The functions sum and product have the inert form Sum and Product,
respectively, which leaves the operation indicated. The function value will
turn the value of the inert form into the actual value.
> Sum(cube(k),k=1..100);
100
X
k3
k=1
154 CHAPTER 8. FINITE SUMS AND PRODUCTS

> value(%);# eval does not work here


25502500
The inert form can be combined with value to obtain a nice layout
> Sum(cube(k),k=1..100):%=value(%);
100
X
k 3 = 25502500
k=1

(For further applications of these inert functions, see the next section.)

8.4 Double sums and products

A double sum is an expression of the type


!
X
m
X
n
X
m
X
n

S = Sm;n = aj;k = aj;k (8.8)


j =m0 k=n0 j =m0 k=n0

where aj;k is a function of both j and k . The sum S depends also on n0


and m0 , but for the time being we do not make this dependence explicit.
A double sum can be thought of as a sum of elements of a sequence
which are themselves sums
X
m
X
n

Sm;n = sj;n sj;n = aj;k :


j =m0 k=n0

The dependence of sj;n on j not only derives from aj;k , but it may also
result from the j -dependence of the range n0 : : : n. In other words, we may
have n0 = n0 (j ) and n = n(j )
2
X
m
X
j

aj;k :
j =m0 k=j

The simplest case is when the range n0 : : : n of the inner sum is inde-
pendent from the summation index of the outer sum. This is illustrated in
the following example
P3 P2 P P 
3 2
S = j =1 k=1
aj;k = j =1 k=1
aj;k
P3
= j =1
(aj;1 + aj;2 )
= a1;1 + a1;2 + a2;1 + a2;2 + a3;1 + a3;2 :
The sum S can be written as
3
X 2
X
S = Sj Sj = aj;k = aj;1 + aj;2 ;
j =1 k=1
8.4. DOUBLE SUMS AND PRODUCTS 155

showing that S is the sum of the rst three elements of the sequence Sj ,
which are themselves sums. Because the upper index of the inner sum
does not depend on the summation index of the outer sum, the order of
summation can be reversed
P3 P2 P
2 3P
j =1 k=1
aj;k = aj;k
Pk2 =1 j =1

= k=1
( a 1;k + a2;k + a3;k )
= a1;1 + a2;1 + a3;1 + a1;2 + a2;2 + a3;2 :

The innermost range does, in general, depend on the outer index. In


the following example, we have n = n(j ) = j
P3 Pj P P 
j =1 k=1
aj;k = 3j =1 j
k=1
aj;k
P1 P2 P
= k=1 a1;k + k=1 a2;k + 3k=1 a3;k
= a1;1 + a2;1 + a2;2 + a3;1 + a3;2 + a3;3 :
In this case, the order of summation cannot be reversed, for otherwise the
range of summation of the k -sum would be unde ned.
Double products behave in the same way as double sums
Q3 Q2 Q
j =1 k=1
aj;k = 3j =1 (aj;1  aj;2 )
= a1;1  a1;2  a2;1  a2;2  a3;1  a3;2 :
As with sums, when the ranges are independent, the order of multiplication
can be reversed.
Sums and products can be combined
P3 Q  P
j =1
2
k=1
aj;k = 3j =1 (aj;1  aj;2 )
= a1;1  a1;2 + a2;1  a2;2 + a3;1  a3;2 :
P Q
Interchanging and alters completely the meaning of the expression
Q2 P  Q
3
k=1 j =1
aj;k = 2k=1 (a1;k + a2;k + a3;k )
= (a1;1 + a2;1 + a3;1 )  (a1;2 + a2;2 + a3;2 )
= a1;1  a1;2 + a1;1  a2;2 + a1;1  a3;2
+a2;1  a1;2 + a2;1  a2;2 + a2;1  a3;2
+a3;1  a1;2 + a3;1  a2;2 + a3;1  a3;2 :

Double sums and products with Maple


Consider the expression
!
4
Y X
j 4
Y
S = (j + k )2
= sj :
j =1 k=1 j =1
156 CHAPTER 8. FINITE SUMS AND PRODUCTS

In the notation of (8.8), we have aj;k = (j + k )2 , so we begin writing a


user-de ned function for a
> a:=(j,k)->(j+k)^2:
Next we write the inner sum as a function, using the inert summation
> s:=j->Sum(a(j,k),k=1..j):
and nally we write out the product
> Product(s(j),j=1..4):%=value(%);
4
!
Y X
j

(j + k ) 2
= 1339800
j =1 k=1

Combining the active function product (or, better still, mul) with the inert
function Sum, the product is evaluated but the sum is not, giving
> product(s(j),j=1..4);
1
! 2
! 3
! 4
!
X 2
X 2
X 2
X 2
(1 + k ) (2 + k ) (3 + k ) (4 + k )
k=1 k=1 k=1 k=1

The following statements extract and evaluate the third operand in the
above expression
> op(3,%):%=value(%);
3
X
(3 + k )2 = 77
k=1

Example 8.12. We wish to count the visible points (see gure 6.5, section
6.3), that lie within a square region on the plane, centered at the origin.
This will involve performing a double summation of their characteristic
function. Because visible points are characterized by the fact that their
coordinates are coprime (theorem 6 of section 6.3), we deduce that the
pattern of visible points in the plane must posses an 8-fold symmetry, since
for any integers x and y we have gcd(x; y ) = gcd(y; x). We denote
by V p(n) the total number of visible points lying within the square n 
x; y;  n, where n is a positive integer. One sees that V p(1) = 8. For
n  2, we must add to this gure eight times the number of the visible
points contained within the triangular region de ned by the inequalities
2xn yx 1: (8.9)
Such inequalities determine the range of double summation of the charac-
teristic function chi(x,y).
> chi:=(x,y)->if igcd(x,y)=1 then 1 else 0 fi:
> Vp:=n->8*(1+add(add(chi(x,y),y=1..n-1),x=2..n)):
> Vp(1),Vp(10),Vp(100),Vp(1000);
8; 256; 24352; 2433536
8.4. DOUBLE SUMS AND PRODUCTS 157

For n = 1, the function Vp gives the correct answer 8, since in this case,
the outer function add has an empty range of summation: (x=2..1).
What is the probability that an integer point chosen at random is vis-
ible? From Theorem 6, this is the same as the chance that two randomly
chosen integers are coprime, and a theorem in number theory states that
the latter probability is equal to 6= 2 . We estimate it by dividing V p(n)
by the total number of integer points in the corresponding box, which is
equal to (2n)2 . For this purpose, we use the largest value computed above
(n = 1000), corresponding to a sample of 4 million points
> evalf(2433536/(2*1000)^2),evalf(6/Pi^2);
:6083840000; :6079271016
Our result is accurate to within three decimal gures.
Exercises
Exercise 8.1. Compute the value of the following expressions (pk denotes
the k th prime number).
100
X 4
X k 2 10
(a) k (k + 1) (b)
k=0 k=0
k +k+1
2

10 
Y
 1 50
X
 
1 50
(c) 1 (d) ( 1)k
k=1
pk k=0
k

5
X 5
X
xn x2n 1
(e) (f ) ( 1)n+1
n=0
n! n=1
(2n 1)!
0 1
10    5 10
X k
20 k Y X
(g ) 2
(h) @ (k + j )A
k=0
2 10 k=1 j =1

5 k +1 5 X  
X X k2 j X n
2k+1 n
(i) (j ) :
k=0 j =1
k+j n=1 k=0
k+1 k
Exercise 8.2. Using Maple, prove that
0 10 12
4
X 5
X
0 1k 2
@ (9 + j )A @ (16 + j )A
4
Y k+1
X j =1 j =1
@ (k 2 + j )A = 2
:
j =1
X
k=1
(1 + j )
j =1
158 CHAPTER 8. FINITE SUMS AND PRODUCTS

Exercise 8.3. Using Maple, prove that


X
n
1 X
n
1 n
(a) k2 = n(n + 1)(2n + 1) (b) =
k=1
6 k=1
k (k + 1) n+1

 
X
n
Y
m
1 1 m+1
(c) k 2 = (n
k
1) 2 n+1
+2 (d) 1 =
k=1 n=2
n2 2 m

!2  
X
n
X
n
X
n
n
(e) k =
3
k (f ) k2 = 2n 2 n (n + 1):
k=1 k=1 k=1
k
Exercise 8.4. Express each of the following sums (products) by means
of the summation (product) symbol. Then, using Maple, nd and prove
formulae for their values. Express the answer in the simplest possible form.

(a) 1  1! + 2  2! + 3  3! +  + (n 1)  (n 1)!

1 1 1 1
(b) + +
1  4 4  7 7  10
+  +
(3n 2)  (3n + 1)
     
4 4 4 4
(c)
1
1
1
9
1
25
   1
(2n 1)2
:

Exercise 8.5. The purpose of this exercise is to carry out computer-


assisted proofs by induction of summation and product formulae. We illus-
trate the procedure for summations | which can be easily generalized to
the case of products. We consider expressions of the form
X
n

ak = F (n) n  n0 (8.10)
k=n0

where
Pn n0 is an integer and F is a given function of n. We de ne S (n) =
k=n0
ak and rewrite equation (8.10) as
S (n) = F (n) n  n0 : (8.11)
To prove (8.11) you must proceed as follows:
 Construct Maple functions for the inde nite summation S (n) and its
conjectured value F (n).
 Using these functions, verify that S (n0 ) = F (n0 ), thereby establishing
(8.11) for n = n0 .
8.4. DOUBLE SUMS AND PRODUCTS 159

 Assume that (8.11) is valid for some n  n0 (this is the induction


hypothesis), and hence express S (n + 1) as a function of F (n)
S (n + 1) = S (n) + an+1 = F (n) + an+1 :

 Verify with Maple that F (n)+ an+1 = F (n +1), proving that equation
(8.11) holds for n + 1.

Following the above procedure, prove the formulae


X
n
1 2
(a) k5 = n (2n2 + 2n 1) (n + 1)2 n1
k=1
12

n
Y1
n
1 x2
n0
k
(b) (1 + x2 ) =
k=0
1 x

X
n
k2 + k 1 1 n+1
(c) = n  1:
k=1
(k + 2)! 2 (n + 2)!

Exercise 8.6. By summing a suitable characteristic function, determine


(a) The number of composite integers between 900 and 1000 (endpoints
included).
(b) The number of odd multiples of 31 lying between 10000 and 11000.
(c) The number of positive divisors of 16200 which are not greater than
150.
(d) The number of integer solutions n to the inequalities
n + 2 + (n + 2)3 > n4 + 1 jnj < 10:
[Hint: interpret the rightmost inequality as a range of summation.]
p have integer coordinates and
(e) The number of points on the plane which
which lie inside the circle with radius 10. How many points lie on the
circumference?
Exercise 8.7 .
 The Euler's totient function (n) counts the number of
positive integers that are smaller than n and relatively prime to it. There
are 4 integers smaller than 8 and relatively prime to it, namely 1,3,5, and
7. Thus, (8) = 4. Construct a user-de ned function for (n), and hence
determine an integer n such that (n)=n < 1=6.
[Hint: plot the elements of the sequence (n)=n. To speed up your com-
putations, you may use Maple's version of , called numtheory[phi](x),
which is very fast.]
160 CHAPTER 8. FINITE SUMS AND PRODUCTS

Exercise 8.8 .
 Let n be an integer. Construct a function SumDigits(n)
whose value is the sum of the decimal digits of n.

8.5 Sums and products as recursive sequences

We consider again the problem of adding or multiplying the elements of a


sequence fak g, in the case in which ak is not given as an explicit function of
the subscript k . This is the case, for instance, when ak is de ned recursively.
Under these circumstances, the function add is of no use, and we must resort
to recursive summation.
We rst rewrite nite sums and products as follows (cf. equations (8.2)
and (8.3))
X
n
X1
n

Sn = ak = ak + an = Sn 1 + an (8.12)
k=n0 k=n0

Y
n n
Y1
Pn = ak = ak  an = Pn 1 a n : (8.13)
k=n0 k=n0

These are recursive formulae, valid for n > n0 . The leftmost summation
and product are valid also for n = n0 , and substituting this value we obtain
the initial conditions
P
Sn0 = Q nk=0 n0 ak = an0
Pn0 = nk=0 n0 ak = an0 :

The initial conditions can be made independent from the sequence fak g as
follows
Sn0 = Sn0 1 + an0 =) Sn0 1 = 0
Pn0 = Pn0 1 a n0 =) Pn0 1 = 1;
extending the range of validity of the recursion formulae (8.12) and (8.13)
to the case n = n0
Sn0 1 = 0; Sn = Sn 1 + an ; n  n0
Pn0 1 = 1; Pn = Pn 1 a n ; n  n0 :
The last formulae yield the following recursive algorithm for computing
sums and products

S 0 P 1 (8.14)
S S + an0 P P  an0
S S + an0 +1 P P  an0 +1
S S + an0 +2 P P  an0 +2
.. ..
. .
8.5. SUMS AND PRODUCTS AS RECURSIVE SEQUENCES 161

Computing Sn or Pn requires iterating this procedure n times.


Example 8.13. Summing a recursive sequence. Let

a0 = 2 at+1 = f (at ) = 1 a2t ; t  0:


Compute
5
X
at :
t=0

We resort to recursive summation, since we do not have an explicit expres-


sion for the summands at . We rst construct a user-de ned function for
f
> f:=a->1-a^2:
Then we initialize the value of the sum, which is to be stored in the variable
s.
> s:=0:
Next we initialize a, and begin summing the rst term
> a:=2:s:=s+a:
(Clearly the above initialization could have been replaced by a:=2:s:=a:.)
Then we update the value of a and add the letter to the sum, as many
times as required.
> a:=f(a):s:=s+a:
> a:=f(a):s:=s+a:
> a:=f(a):s:=s+a:
> a:=f(a):s:=s+a:
> a:=f(a):s:=s+a:
Finally, we display the value of the sum
> s;
15749063
Two comments are in order here. First, no subscript was necessary to carry
out this computation, and second, the process of summation amounts to
repetition of the same expression. In the next chapter, we will learn how
to carry out this repetition automatically.

Exercises
Exercise 8.9. Consider the following recursive sequence in Q (x)
x
g0 = x gt+1 = ; t  0:
gt + 1
Show that
3
Y x4
gt = :
t=0
x2 x 1
162 CHAPTER 8. FINITE SUMS AND PRODUCTS

Exercise 8.10. Let


h0 = 1 h1 = 1 ht+1 = 2 ht ht 1 ; t  1:
Compute
5
X 1
:
t=1
ht
Chapter 9

Elements of programming
In this chapter, we introduce three universal programming tools: iteration
(the do-structure), conditional execution (the if-structure), and procedures
(user-de ned functions). Only the rst one is new to us. We have encoun-
tered simple instances of the if structure in the context of characteristic
functions, and we have used extensively the arrow operator -> to construct
user-de ned functions consisting of a single statement.

9.1 Iteration

The do-structure allows repeated execution of a statement or a block of


statements, which is one of the things computers are good at.
We illustrate the use of the do-structure for the construction of a re-
cursive sequence. We wish to verify that the element 3 of the recursive
integer sequence
0=1 5
t+1 = f ( t ) = t + 1; t  0;
has 8 decimal digits. As usual, we de ne the function f , initialize , iterate
as many times as required, and nally display the value of
> f:=a->a^5+1:
> a:=1:
> a:=f(a):
> a:=f(a):
> a:=f(a):
> a >= 10^7 and a < 10^8;
true
The statement a:=f(a): is repeated three times. This process can be
automated by means of the do-structure, as follows
163
164 CHAPTER 9. ELEMENTS OF PROGRAMMING

> a:=1:
> to 3 do
> a:=f(a)
> od:
> a;
39135394
The same result may be achieved with the following simpler construction,
which makes use of ditto variables
> 1:
> to 3 do
> f(%);
> od:

> %;
39135394
Next we consider the problem of constructing Pascal's triangle. Recall
that the nth row of the triangle is given by the nite sequence
n n n
0 ; 1 ; ::: ; n
which is best dealt with by a user-de ned function
> row:=n->seq(binomial(n,k),k=0..n):
The following command generates the rst eight rows of Pascal's triangle
(n ranging from 0 to 7)
> row(0);row(1);row(2);row(3);row(4);row(5);row(6);row(7);
This time the statements to be repeated are not identical, but they depend
on the index n increasing in unit steps from 0 to the prescribed maximal
value. The do-structure can be made to assume the control of the integer
variable n, as follows
> for n from 0 to 7 do
> row(n)
> od;
1
1; 1
1; 2; 1
1; 3; 3; 1
1; 4; 6; 4; 1
1; 5; 10; 10; 5; 1
1; 6; 15; 20; 15; 6; 1
1; 7; 21; 35; 35; 21; 7; 1
9.1. ITERATION 165
The value of n is initialized to 0, and then increased by 1 each time. For
every value of n the statement row(n) is executed, until n exceeds the
target value of 7.
Syntax
The syntax of the do-structure is the following:
> for n from start by step to nish do
> statement;
> 
> statement
> od;
The loop control variable n is initialized at start and then increased by
step until its value exceeds that of nish (or until it becomes smaller than
nish, if step is negative). The expressions start, step, and finish must
have integer, rational, or oating-point value.
The body of the do-structure consists of an arbitrary number of state-
ments, each statement in the block being executed in correspondence of
each value assumed by n. The loop control variable can be used within
the structure as any other variable, but its value cannot be changed inside
the loop. The last statement in the body of the structure does not require
a terminator. To make the do-structure visible, it is good programming
practice to indent the statements in the body of the loop, inserting a few
blank characters.
The output of the statements is displayed if od is followed by a semicolon,
and suppressed if od is followed by a colon, regardless of which terminator
follows the individual statements.
The from and by options may be omitted, in which case the value of both
start and step defaults to 1. If the loop control variable is not needed, the
for option may be omitted, in which case Maple de nes its own loop control
variable. If the to option is omitted, the loop is in nite, and presumably
it will be terminated by other means.
In the following examples, observe carefully the values assumed by the
loop control variable on exit. Also note that the whole loop is logically
equivalent to a single command.
> for i from 2 by 2 to 7 do i od:
2
4
6
> i;
8
> for i from 2 by -3 to -1 do i od;
2
166 CHAPTER 9. ELEMENTS OF PROGRAMMING

1
> i;
4
If the range is empty, the loop is not executed, and the value of the loop
control variable is not modi ed
> for i from 2 by -1 to 3 do i od;
> i;
2
To display the output of selected statements in a loop (rather than of all
or no statements, as determined by the terminator of od), Maple provides
the standard library function print, which always displays its value within
the body of a do-structure, in the form of an expression sequence.
> x:=1:
> for n to 3 do
> x:=x+igcd(n,x):
> print(n,%)
> od:
1; 2
2; 4
3; 5
The colon after od suppresses all output, except that of the print state-
ment, which is the only output to be shown.
Example 9.1. An instructive comparison between two similar construc-
tions using do and seq is as follows
> 2:
> for i to 3 do
> %*i
> od;
2
4
12
> 2:
> seq(%*i,i=1..3);
2; 4; 6
Make sure you understand how and why these two results di er.
9.1. ITERATION 167
Summing the elements of a recursive sequence. Compute
the sum P5t=0 xt , with xt given by (9.0), using the recursive summation
Example 9.2.

algorithm (8.14).
> x:=0:
> s:=x:
> to 5 do
> x:=f(x):
> s:=s+x:
> od:
> s;
711
Example 9.3. Constructing a nested expression. Compute the value of
the following expression
12 + 1
32 + 1
52 + 1
72 + 912
> 9^2:
> for i from 7 by -2 to 1 do
> i^2+1/%
> od:
> %;
997280
897949
Example 9.4. Plotting a recursive sequence. We wish to plot the ele-
ments of the rational sequence
x0 = 1=4 xt+1 = 1 2x2t ; t  0: (9.1)
As usual, we rewrite the recursion formula as xt+1 = f (xt ), with f (x) =
1 2x2 . In the recursive computation of xt , the index t plays no role, and
the successive values of xt are to be stored in the single variable x. The
plotting routine requires a list L = [[1; x1 ]; [2; x2 ]; : : :], containing the points
to be plotted, vs. the corresponding index. Such list L will be represented
as an expression sequence of two-element lists, which we initialize to the
NULL value. At the end of the computation, L is then turned into a list
for plotting. The sequence (9.1) is rational, since x0 is rational, and the
recursion involves only rational operations. However, an inspection of the
168 CHAPTER 9. ELEMENTS OF PROGRAMMING

rst few elements reveals that numerator and denominator of xt grow at


an alarming rate
x1 = ;
7 x2 =
17 223 81343
8 32 ; x3 = 512 ; x4 = 131072 :
Indeed, the number of digits of numerator and denominator of xt approx-
imately doubles at each step, due to the fact that f squares its argument
(the denominator of x10 has 309 digits!). So it would be impossible to plot,
say, the rst 100 elements of the sequence (9.1), using an exact represen-
tation. We shall therefore opt for the oating-point representation of xt
(see section 5.2), which is inexact, but which will render the computation
feasible, since it allocates a xed amount of information for each xt .
> f:=x->1-2*x^2:
> x:=0.25:
> L:=NULL:
> for t to 100 do
> x:=f(x):
> L:=L,[t,x]:
> od:
> L:=[L]:
> plot(L);

0.5

0 20 40 60 80 100

-0.5

-1

Note the very irregular behaviour of this sequence, which is chaotic, using
the jargon of the theory of dynamical systems [6].
9.1. ITERATION 169
The in option
Recall that functions such as seq, add, mul, etc., accept any expression as
range, not just a sequence of integers.
> ifactor(3960);
(2)3 (3)2 (5) (11)
> [seq(expand(k),k=%)];
[8; 9; 5; 11]
A similar construction is available in a loop, using the in option
> for k in ifactor(3960) do
> expand(k)
> od;
8
9
5
11
> L:=NULL:
> for k in ifactor(3960) do L:=[L,expand(k)] od:
> L;
[[[[8]; 9]; 5]; 11]
The while option
The while option a ords an alternative way to terminate an iteration. Its
syntax is the following
> while logical expression do
> statements
> od;
The logical expression in the heading is evaluated. If its value is false, the
loop is exited. If it is true, the body of the loop is executed, after which
the logical expression is evaluated again, etc. Evaluation does not require
the use of evalb.
> x:=2:
> while x < 100 do
> x:=x^2;
> od;
x := 4
x := 16
x := 256
The while option is the most general one, in the sense that the e ect of
any other combination of options can be reproduced using the while option
170 CHAPTER 9. ELEMENTS OF PROGRAMMING

alone. The while option can be used in conjunction with any other option.
For instance, let start, step, and finish have integer values, and let step
be positive. The structure
> for k from start by step to finish do
> statements
> od:
can be reproduced as follows
> k:=start:
> while k <= finish do
> statements;
> k:=k+step
> od:
If step is negative, then the inequality tested by the while option should
be reversed.
Example 9.5. Compute the number of primes less than 100.
> for n while ithprime(n) < 100 do od:
> n-1;
25
(Why is the required output n 1 and not n?)
Example 9.6. Use the while option to compute Ob , the smallest positive
integer n for which n! is greater than bn . (This function was considered in
an exercise of chapter 4.) Here we compute the value of O5 .
> H:=(n,b)->n!<=b^n:
> for n while H(n,5) do od;
> n;
12
Note that the body of the loop is empty. All the work is done by the
loop control functions. By nesting the above loop inside another loop that
controls the value of b, we can compute several elements of the sequence
Ob . These are the rst 10 of them
> for b to 10 do
> for n while H(n,b) do od:
> print(b,n)
> od:
1; 2
2; 4
3; 7
4; 9
5; 12
6; 14
9.1. ITERATION 171

7; 17
8; 20
9; 22
10; 25
Exercises
Exercise 9.1. In the following exercises you must use the do-structure.
(a) Display the square of the rst 10 prime numbers. Hence do the same
using the function seq.
(b) Compute the sum of the rst 10 prime numbers. (When you are sure
that your code is working, suppress all intermediate output within the loop.)
Hence check your result with the function add.
(c) Compute the product of the rst 10 prime numbers. Hence check your
result with the function mul.
(d) Let
p(x) = x (3 + x (6 + x (9 + x (12 + x (15 + x))))):
Show that p(x)=x is irreducible.
(e) Show that the element x20 of the following sequence of integers
x0 = 3 x1 = 5 xt+1 = f (xt ; xt 1 ) = 3 xt 2 xt 1 ; t1
is equal to 221 + 1.
Exercise 9.2. Consider the following recursive sequence of rationals

x 2
x0 = 0 xt+1 = f (xt ) = t ; t  0: (9.2)
xt + 2
(a) Compute the element x10 , without displaying any intermediate output.
(b) Compute the rst 10 elements of the sequence (9.2), displaying the
value of t and xt at each step.
(c) Compute the sum of the rst 10 elements of the sequence (9.2).
(d) Plot the elements of the sequence (9.2) for t in the range 30; : : : ; 100,
connecting points with segments.
Exercise 9.3. In the following exercises you must use the while option
of the do-structure.
(a) Display the positive cubes smaller than 500.
(b) Compute the smallest integer greater than 1 which is relatively prime
to 9699690.
(c) Compute the smallest integer n > 1 for which n2 1 is divisible by 87.
(d) Compute the smallest positive integer n for which n2 + n + 41 is not
prime.
172 CHAPTER 9. ELEMENTS OF PROGRAMMING

(e) Compute the smallest positive n which is a multiple of 3, and for which
2n > n4 .
(f ) Consider the following recursive sequence of complex numbers
z0 = 2 i
4
zt+1 = zt2 + i; t  0:
3
Compute the smallest value of t for which jzt j > 105.
Exercise 9.4. We consider the number qn of composite integers following
the nth prime pn . Thus, q4 = 3, because the fourth prime p4 = 7 is followed
by the 3 composite integers 8; 9; 10. For n > 1, qn is always odd (make sure
you believe this).
(a) Compute the smallest prime pn which is followed by at least 9 composite
integers. Display also the corresponding value of n.
(b) Let at be the smallest value of n for which qn  t. Thus, pa is the
smallest prime which is followed by at least t composite integers. (Think
t

about it. Read the de nition again. In the previous problem you have
computed a9 and pa9 .) Compute and display t; at , and pat , for all odd t
smaller than 20 (excluding t = 1).
Exercise 9.5. Exponentials grow faster than any power. In this prob-
lem, we compute the integer n > 1 at which the exponential sequence 2n
overtakes the power ne , where e is a given positive integer. We call this
number e . Compute the rst 10 elements of the sequence
1; 2 ; 3 ; : : :
Exercise 9.6 .
 Compute the largest integer less than 1000 that can be
expressed as a sum of two squares (e.g., 5 = 12 + 22 ). No intermediate
output should be displayed.
Exercise 9.7 .
 Consider the set of natural numbers, the sum of whose
decimal digits is divisible by 7
f0; 7; 16; 25; 34; 43; 52; 61; 70; 106 : : :g:
Compute the number of elements of this set which are smaller than 1000.
Exercise 9.8 .
 We de ne an in nite recursive sequence S = s1 ; s2 ; : : : of
elements of the set f1; 2g. We rst let S = 1; 2; 1, and then we apply
repeatedly the substitution: S 7! S; 1; S; 2; S; 1; S . After t substitutions,
S will have 4t+1 1 elements. We then de ne the sequence
X
n
0 = 0 n = sk ; n  1:
k=1
9.2. STUDY OF AN EVENTUALLY PERIODIC SEQUENCE 173
Plot the rst 44 elements of the sequence 0; z0 ; z1; z2 ; : : :, where zn are
complex numbers de ned as
X
n
zn = e i k =3 :
k=0

Connect points with segments. (The result, shown below, is an approxima-


tion to a fractal called Koch's snow ake.)

9.2 Study of an eventually periodic sequence

We now apply various techniques developed so far to the study of the struc-
ture of a family of eventually periodic sequences of integers, de ned recur-
sively.
Take a four-digit integer x0 , whose digits are not all the same: (x0 =
1066). Rearrange the digits to make the largest possible number (6610) and
the smallest (0166). Subtract the smallest from the largest (6610 0166 =
6444 = x1 ). It can be shown (see exercises) that the result is a 4-digit
integer whose digits are not all the same. By repeating the above procedure,
we obtain a recursive sequence of four-digit integers: xt+1 = F (xt ), t  0.
The same construction can be carried out in the case of n-digit integers,
for arbitrary n > 1
xt+1 = Fn (xt ) t  0; n > 1: (9.3)
First some examples:
n=2: 82; 54; 9; 81; 63; 27 45; 9; 81; : : :
n=4: 1066; 6444; 1998; 8082; 8532; 6174; 6174; : : :
These sequences are eventually periodic, with period 5 and 1, respectively,
and transient length 2 and 7, respectively. Eventual periodicity is easy
to explain: the domain of Fn is nite, and therefore we must eventually
174 CHAPTER 9. ELEMENTS OF PROGRAMMING

encounter an integer that has appeared before. From that point on, the
sequence will repeat.
We wish to explore the case n = 4 in full, producing a computer-assisted
proof that all 4-digit sequences eventually reach 6174.
We need a user-de ned function for Fn . Decimal digits are to be
stored backwards in a 4-element list: 3861 <-> [1,6,8,3], and we must
be able to switch easily from an integer to the corresponding list, and vice
versa. For this purpose we develop two conversion functions. The function
int2dig(x,n) produces the list of the rst n digits of the integer x, begin-
ning with the least signi cant one. If n is greater than the number of digits
of x, the function will ll the missing spaces with zeros. This function is a
variant of the function dgt developed in section 5.1 to compute the digits
of a rational number.
> int2dig:=(x,n)->[seq(irem(iquo(x,10^(i-1)),10),i=1..n)]:
Its inverse of int2dig is dig2int(L), where L is a list of an arbitrary
number of non-negative integers
> dig2int:=L->add(op(i,L)*10^(i-1),i=1..nops(L)):

Next we construct the largest and smallest n-digit integers obtainable


from x. For this purpose, we use the standard library function sort, which,
by default, sorts the elements of a list in ascending order
> big:=(x,n)->dig2int(sort(int2dig(x,n))):
To sort in descending order, we supply sort with an optional second ar-
gument, which is the symbolic name of a Boolean function s(a; b) of two
arguments, specifying the criterion for sorting. Speci cally, s(a; b) should
return true if a is to precede b in the sorted list, and so the function for
sorting in descending order is
> s:=(a,b)->not a < b:
whence
> small:=(x,n)->dig2int(sort(int2dig(x,n),s)):
As with map, the sorting function may be supplied directly, as a procedure
de nition
> small:=(x,n)->dig2int(sort(int2dig(x,n),(a,b)->not a < b)):
Finally, the desired function for the recursion (9.3) is
> F:=(x,n)->big(x,n)-small(x,n):

We now develop an algorithm to compute a given sequence up to and


including its periodic part. Such a sequence will be stored in an expres-
sion sequence called S, to be initialized to NULL, the zero-length expression
sequence. The variable NewS represents the sequence at the successive it-
eration. Periodicity is detected from the appearance of an element that
already belongs to the sequence. To achieve this, the expression sequence
is converted into a set, and each new element is checked for membership to
9.2. STUDY OF AN EVENTUALLY PERIODIC SEQUENCE 175
that set.
> n:=4:
> x:=1066:
> S:=NULL:
> NewS:=x:
> while not member(x,fSg) do
> S:=NewS:
> x:=F(x,n):
> NewS:=NewS,x
> od:
The variable S now contains all elements up to the rst repetition, while the
current value of x is that corresponding to the beginning of the repeating
block. For convenience, we convert S into a list, and then identify the
beginning of periodicity
> L:=[S]:
> for t while x <> op(t,L) do od:
Now the transient length is t-1. We display transient and repeating block
using the selection operator (see section 6.1)
> L[1..t-1],L[t..nops(L)];
[1066; 6444; 1998; 8082; 8532]; [6174]
We can now perform a global analysis of the sequence, by considering
all possible 4-digit initial conditions. The latter will be stored in a set
called ic. To avoid duplication, among the integers sharing the same digits,
we consider only the smallest one. We must also eliminate integers with
identical digits.
> ic:=fseq(small(x,n),x=1..9998)g minus fi*1111$i=1..8g:
The expression i*1111$i=1..8, which makes use of the sequence operator
$, is shorthand for the expression seq(i*1111,i=1..8)
> cycle:=fg:
The variable cycle, initialized to the empty set, is to contain the rst
element of each repeating block (also called a limit cycle). The computation
requires a double do-loop: the outer loop runs through all initial conditions
x0, while the inner loop computes the corresponding orbit. The latter
will be represented as a set, since we are only interested in detecting the
beginning of periodicity.
> for x0 in ic do
> #----------- compute orbit starting at x0, until repetition
> orbit:=fx0g:
> x:=F(x0,n):
> while not member(x,orbit) do
> orbit:= orbit union fxg:
> x:=F(x,n)
176 CHAPTER 9. ELEMENTS OF PROGRAMMING

> od:
> #------------------------- store first element of cycle
> cycle:=cycle union fxg
> od:
> cycle;
f6174g
We have shown that all orbits eventually reach the cycle beginning with
6174, which we know to have period 1. In the parlance of the theory of
dynamical systems, we shall say that f6174g is a global attractor for the
system (9.3).
Exercises
Exercise 9.9. Let S be the set of all nite non-empty subsets of Z. Let
s 2 S. Because s is nite and non-empty, it has a largest element M and
a smallest element m. We consider the set s0 obtained from s by replacing
m by m + 1 and M by M m. This is also nite and non-empty, and it is
uniquely determined by s. So we have a function f : s 7! s0 of S into itself,
given by
f : s 7! f (s) = ((s n fmg) n fM g) [ fm + 1g [ fM mg: (9.4)
We construct recursive sequences in S , via f
s0 = s st+1 = f (st ); t  0: (9.5)
For example, the initial condition s0 = f 1; 2; 4g leads to an eventually
periodic sequence, with transient length 5 and period 3
f 1; 2; 4g 7! f0; 2; 5g 7! f1; 2; 5g 7! f2; 4g 7! f2; 3g
7! f1; 3g 7! f2g 7! f0; 3g 7! f1; 3g 7!   
(a) Implement the function f in (9.5) with Maple.
(b) Explore the behaviour of the sequence (9.5).
(c) Prove that the sequence (9.5) is eventually periodic, for any choice of
s0 .
Exercise 9.10. Let x be a positive integer. We construct a new integer
f (x) according to the following rule

f (x) = 3x=x2+ 1 ifif xx is odd
is even. (9.6)
Explore the behaviour of the associated recursive sequence. This is the cel-
ebrated `3x +1' problem. The main conjecture | that all orbits eventually
reach the cycle (4; 2; 1) | is still unproved.
9.3. CONDITIONAL EXECUTION 177
Exercise 9.11 .
 Prove that the map Fn of equation (9.3) is well-de ned,
in the sense that if x is an n-digit integer whose digits are not all the same,
so is Fn (x).

9.3 Conditional execution



Conditional execution, represented by the if-structure, implements the
process of decision-making in a programming language. Decisions are made
based on the truth or falsehood of logical expressions. We have already met
the if-structure in chapter 3, to construct characteristic functions.
In the simplest instance, the if-structure assumes the following form
> if logical expression then
> statements
> fi;
If the value of the logical expression is true, the statements are executed.
Otherwise, the control jumps to the statement following the fi statement.
The general form of the if-structure is the following:
> if logical expression 1 then
> statements 1
> elif logical expression 2 then
> statements 2
..
.
> else
> default statements
> fi;
The logical expression 1 is evaluated. If it is true, then statements 1 are
executed, and the structure is exited. Otherwise, logical expression 2 is
evaluated, and so on, sequentially for all elif statements (if any). Finally,
if there is an else statement and all logical expressions in the structure
are false, the default statements are executed. The logical expressions are
evaluated automatically, without the need of using evalb.
Example 9.7. Piecewise-de ned functions. These are functions whose
value is given by distinct expressions in distinct regions of the domain. One
such function is that converting marks (typically rational numbers between
0 and 100) into grades (typically elements of the set fA; B; C; D; E; F g),
e.g., 8 F if 0  x < 40
>
>
>
< ED ifif 40
>  x < 50
f (x) = C if 60  50

x < 60
x < 70 (9.7)
>
>
>
>
: B if 70  x < 80
A if 80  x  100.
178 CHAPTER 9. ELEMENTS OF PROGRAMMING

We shall agree to return the NULL value when the argument x is out of
range.
> f:=x->if x < 0 or x > 100 then
> NULL
> elif x < 40 then
> F
> elif x < 50 then
> E
> elif x < 60 then
> D
> elif x < 70 then
> C
> elif x < 80 then
> B
> else
> A
> fi:
The rst logical expression is true only if x is out of range. If this is not the
case, then x  0, necessarily, so that the single inequality x < 40 suÆces
to check the two inequalities in (9.7), and so on. If the control reaches
the keyword else, then all previous logical expressions in the structure are
false, whence 80  x  100, and no further check is required for the grade
A.
(An alternative way of constructing piecewise-de ned functions is af-
forded by the standard library function piecewise.)
Example 9.8. We develop an algorithm for nding a rational approxima-
tion to an irrational number lying in the unit interval [0; 1]. The algorithm
is based on repeated construction of mediants p (the mediant of two ration-
als was de ned in (2.20)). We choose = ( 5 1)=2. (This number has
a special status: it is the irrational between 0 and 1, which is the most
diÆcult to approximate by rationals.) We begin by de ning the function
med for the mediant, and the small parameter small, which represents the
desired accuracy of the result.
> med:=(l,r)->(numer(l)+numer(r))/(denom(l)+denom(r)):
> small:=1/1000:
> alpha:=evalf((sqrt(5)-1)/2):
The variable alpha has been assigned a float value, in order to allow the
evaluation of the expression abs(m-alpha) >= small to Boolean (see be-
low). The starting interval is the unit interval, with endpoints left and
right. The iteration is carried out within a do loop controlled via the
while option.
> left:=0:
9.4. PROCEDURES 179
> right:=1:
> m:=med(left,right):
> while abs(m-alpha) >= small do
> if m < alpha then
> left:= m
> else
> right:=m
> fi:
> m:=med(left,right)
> od:
> m;
21
34
We have implicitly assumed that the expression abs(m-alpha) >= small
will eventually evaluate to false, thereby ensuring that the loop is not exe-
cuted inde nitely (see exercises).
Exercises
Exercise 9.12. Consider the following irrational numbers in the unit in-
terval (e = 2:718 : : : is Napier's constant)
p
5 1 ; p2 1;  3; e 2:
2
By repeated iterations of the mediant method, determine rationals approx-
imating these numbers within 10 6. Compare the size of denominators.
Exercise 9.13 .
 Prove that for any choice of in the unit interval, the
do-loop of the mediant algorithm does eventually terminate.

9.4 Procedures

A function de ned by means of the arrow operator -> is a simple instance of
a more general construct called a procedure , which we shall brie y describe
in this section. We recall the syntax of the arrow operator
> name:=(arguments sequence)->expression;
The following function adds 1 to each operand of an arbitrary object
> AddOneTo:=anything->map(x->x+1,anything):
The same function can be de ned as a Maple procedure as follows
> AddOneTo:=proc(anything)
> map(x->x+1,anything)
> end:
and then called as before
180 CHAPTER 9. ELEMENTS OF PROGRAMMING

> AddOneTo(f1,0,-22,bg), AddOneTo(a=b);


fb + 1; 21; 1; 2g; a + 1 = b + 1
The range of valid data types for the argument anything is broad, but not
quite arbitrary. For instance, the function call AddOneTo([fag]); would
produce an error termination, resulting from the attempt of adding an
integer to a set.
The proc construct allows the user to de ne functions comprising more
than one statement. A procedure would normally feature a control of the
arguments' type, as well as the use of local variables. The syntax is the
following:
> name:= proc(arguments::type sequence);
> [local variables sequence;]
> [option options sequence;]
> statements
> end;
The arguments::type sequence is an expression sequence containing the ar-
guments' names. Each name may (and indeed should) be followed by its
required data type, separated by two colons. If more than one data type is
acceptable, these should be listed as elements of a set.
Local variables are used for temporary storage. They are invisible from
outside the procedure and unrelated to any variable with the same name
that may occur elsewhere.
The meaning of the option sequence will be brie y illustrated below,
in the context of recursive procedures.
Example 9.9. The following procedure transforms the list of coeÆcients
of a polynomial into a polynomial in the indeterminate x.
> Coeff2Poly:=proc(polylist::list, x::symbol)
> local i, degree:
> degree:=nops(polylist):
> 0:
> for i to degree do
> % + polylist[i] * x^(degree - i)
> od
> end:

> Coeff2Poly([1,1,c^2+1,1], y);


y3 + y2 + (c2 + 1) y + 1
Example 9.10. The following procedure generates the list of primes lying
between two integers a and b (a and b included).
> PrimesBetween:=proc(a::integer, b::integer)
> local L, p:
9.4. PROCEDURES 181
>
> L:=[]:
> p:=nextprime(a-1):
> while p <= b do
> L:=[op(L),p]:
> p:=nextprime(p)
> od:
> L
> end:
> PrimesBetween(1000,1100);

[1009; 1013; 1019; 1021; 1031; 1033; 1039; 1049; 1051; 1061; 1063;
1069; 1087; 1091; 1093; 1097 ]
The argument a must be an integer, being used by the function nextprime.
This requirement is extended to the argument b for consistency. The two
variables p and L are local. The initialization p:=nextprime(a-1) ensures
that if a is prime, then it is included in the list. The output is stored in
the variable L, which is initialized to the empty list. The reader is invited
to compare the running time of this function with that of the simpler but
slower construct developed in chapter 6, using select. (To compute run
time, see ?time.)
Example 9.11. We construct a function freq that computes the fre-
quency of occurrence of the elements of an arbitrary list. For instance, in
the list [a,b,ba,b,ba,b,ab,b], the elements a and ab appear once, ba
twice, and b four times.
> freq([a,b,ba,b,ba,b,ab,b]);
[a; 1]; [b; 4]; [ba; 2]; [ab; 1]
The output is to be organized in the form of a sequence of two-elements
lists, containing each value with its frequency.
> freq:=proc(L::list)
> local l, x;
> seq([x, nops(select((l,x)->evalb(l=x), L, x))], x=fop(L)g)
> end:
The expression x=fop(L)g causes the control variable x in seq to run
through all distinct elements of the list L, which is turned into a set to
eliminate repetitions. The Boolean function (l,x)->evalb(l=x) is ap-
plied by the function select to all elements of L. Its second argument x
is supplied as the third optional argument of select. The result of the
selection is the list of those elements of L which are equal to x. Finally, the
latter are counted by nops.
As an application, we consider the sequence of remainders of division of
the rst 1000 odd primes by 4. For instance, if we divide by 4 the primes
182 CHAPTER 9. ELEMENTS OF PROGRAMMING

11 and 13, we obtain the remainders 3 and 1, respectively. We count their


frequency.
> [seq(irem(ithprime(n),4),n=2..1001)]:
> freq(%);
[1; 495]; [3; 505]
What have we learned from this experiment? First, the only possible re-
mainders seem to be 1 and 3 (this is easy to explain: think about it).
Second, the primes of the form 4 n + 1 (remainder 1) and those of the form
4 n + 3 (remainder 3) seem to be equally abundant (this is a celebrated
theorem of number theory).
Recursive procedures
A procedure is said to be recursive if it calls itself.
As an application, we consider the problem of representing the element
Xt of a rst-order recursive sequence as an explicit function of t
X0 = X Xt = f (Xt 1); t  1: (9.8)
Here f is a given function, and the initial value X is a given constant (an
element of the domain of f ). The element Xt is computed from X0 by iter-
ating the recursion (9.8) t times, which we have done earlier in this chapter
by means of the do-construct. The use of recursive function call amounts
to a literal translation into Maple of equation (9.8). It is computationally
equivalent to a do-loop, but logically simpler.
We consider the recursive sequence of rational numbers
X +1
X0 = 1 Xt = f (Xt 1 ) = t 1 ; t  1: (9.9)
Xt 1 + 2
We rst de ne the function f
> f:=x->(x+1)/(x+2):
Then we write a procedure for the function t 7! Xt
> X:=proc(t::nonnegint)
> option remember:
> if t = 0 then
> 1
> else
> f(X(t-1))
> fi
> end:
The argument t is a non-negative integer.
The statement option remember
causes Maple to remember the intermediate values of the recursion, avoid-
ing re-computations. The rest of the procedure is a direct translation of
equation (9.9).
9.4. PROCEDURES 183
Example 9.12. The following recursive procedure returns the leaves (in-
nermost operands) of the tree representing a Maple expression x, in the
form of an expression sequence.
> leaves:=proc(x)
> local y
> if (nops(x) = 1) then
> x
> else
> seq(leaves(y), y=x)
> fi
> end:
If x has more than one operand, we apply the function leaves recursively
to all operands.
Exercises
Exercise 9.14 .
 Let (x1 ; y1 ); : : : ; (x4 ; y4) be four points on the plane,
with integer or rational coordinates. Write a procedure that returns true
if these points are vertices of a square, and false otherwise.
Chapter 10

Vector spaces
This chapter contains some elements of linear algebra: the construction
of a vector space (in the limited context of direct product of elds), the
arithmetic of its elements (the vectors ), and the study of a most important
class of functions de ned over vector spaces (represented by matrices ).

10.1 Cartesian product of sets

We describe a general procedure for constructing new sets from old ones,
which is analogous to the construction of a two-dimensional plane or a
three-dimensional space, from a one-dimensional line.
Let T be a set. We denote by T 2 = T  T the set of ordered pairs of
elements of T , called the Cartesian product of T with itself. Thus, T 2 is
the collection of elements v = (v1 ; v2 ) with v1 ; v2 2 T ; the requirement that
the pair be ordered means that (v1 ; v2 ) 6= (v2 ; v1 ). Similarly, one de nes
T 3 = T  T  T , the set of ordered triples (v1 ; v2 ; v3 ) of elements of T , and
in general the set T n of ordered n-tuples
T = T|  T {z    T} = f(v1 ; v2 ; : : : ; v )g
n
n v
k 2 T; k = 1; : : : ; n:
n times
The elements of T are called vectors.
n

Example 10.1. Vectors.


(1; 1; 3) 2 Z3 1 ; 1 2 Q 2
p 3
( 2 + i; 3i) 2 C 2 (x + x + 1; 2x 1; x; x) 2 Z[x]4:
2

If T  U , then T  Un
, for all positive n (why?). In particular, for
n

every positive integer n we have the chain of inclusions


Nn Z Q R C :
n n n n

185
186 CHAPTER 10. VECTOR SPACES
Example 10.2. Let T = f0; 1g. Then T 3 has 23 = 8 elements
T 3 = f(0; 0; 0); (0; 0; 1); (0; 1; 0); (0; 1; 1); (1; 0; 0); (1; 0; 1); (1; 1; 0); (1; 1; 1)g:
Example 10.3. Let I = [0; 1] be the unit interval
I = fx 2 R j 0  x  1g: (10.1)
Then I 2  R2 is a square of unit area, while I 3 R3 is a cube of unit
volume.
In the de nition of Cartesian product of sets, there is no requirement
that the sets involved be identical copies of the same set. Thus, T  S is
de ned as the set of ordered pairs v = (t; s) with t 2 T and s 2 S .
Example 10.4. Let T = f1; 2; 3g, and U = f 1; 2g. Then
T  U = f(1; 1); (1; 2); (2; 1); (2; 2); (3; 1); (3; 2)g:
Example 10.5. Let T be a line and S a circle. Then T  S is an in nite
cylinder. If I is the unit interval (10.1), then I  S is an annulus.
Example 10.6. Let T be any set, and S = f1; 2; : : : ; ng. Then T  S
can be thought of as the collection of n copies of T , indexed by the integers
1; 2; : : : ; n.

10.2 Vector spaces

We introduce the notion of a vector space V , in the context of a Cartesian


product of elds. This will suÆce for our purposes. For a more general
de nition, consult the last chapter of this book.
Let F be a eld (for instance, F = Q ; R; C ; Q (x), etc.). Then F is
equipped with the two arithmetical operations of sum and multiplication,
which can be performed unrestrictedly along with their inverses (subtrac-
tion and division), excluding division by zero. These operations in F allow
us to de ne certain operations in the Cartesian product V = F n , which will
make it into a vector space. In V , the elements of F will be called scalars.
We begin with the case n = 2. Let V = F 2 , let u = (u1 ; u2 ) and
v = (v1 ; v2 ) be elements of V , and let 2 F . We de ne the sum u + v and
the scalar multiplication v as follows

addition: u + v = (u1 ; u2 ) + (v1 ; v2 ) = (u1 + v1 ; u2 + v2 )


scalar multiplication: u = (u1 ; u2 ) = ( u1 ; u2 ):
These operations satisfy certain properties, which derive directly from
the arithmetic in a eld. We list them below, leaving some of the proofs as
exercises.
10.2. VECTOR SPACES 187

1. The sum is commutative


u + v = v + u:
Indeed,
u + v = (u1 ; u2 ) + (v1 ; v2 ) = (u1 + v1 ; u2 + v2 ) = (v1 + u1 ; v2 + u2 )
= (v1 ; v2 ) + (u1 ; u2 ) = v + u:
2. For all u; v; w 2 V we have the associative law:
(u + v ) + w = u + (v + w)
which says that the order with which addition of vectors is performed does
not matter.
3. The element O = (0; 0) is such that for each v we have v + O =
O + v = v:
v + O = (v1 ; v2 ) + (0; 0) = (v1 + 0; v2 + 0) = (v1 ; v2 )
= (0 + v1 ; 0 + v2 ) = (0; 0) + (v1 ; v2 ) = O + v:
4. The element ( 1) v is such that v + ( 1) v = O:
v + ( 1)v = (v1 ; v2 ) + ( 1)(v1 ; v2 ) = (v1 ; v2 ) + ( 1v1 ; 1v2)
= (v1 ; v2 ) + ( v1 ; v2 ) = (v1 v1 ; v2 v2 ) = (0; 0) = O:
5. The following distributive laws hold:
(u + v ) = u + v; ( + ) v = v + v; ( ) v = ( v ):
6. There is an identity for scalar multiplication: 1 v = v .
The generalization of all the above de nitions to the case of arbitrary
positive n is straightforward. If u = (u1 ; : : : ; un ) and v = (v1 ; : : : ; vn ), we
have
u  v = (u1  v1 ; : : : ; u n v
n ) v = ( v1 ; : : : ; v ):
n

A Cartesian product V = F n with the operations described above is an


example of a vector space of dimension n over F . We remark that vector
spaces are more general than Cartesian products of elds.
In a vector space, multiplication by a scalar combines a vector with
a scalar, to yield another vector. There is no multiplication between two
vectors that resembles multiplication between numbers. There is instead
the scalar product, which is a binary operation turning a pair of vectors
into a scalar. As before, we de ne it in the case in which V is a Cartesian
product of elds.
188 CHAPTER 10. VECTOR SPACES
Let u = (u1 ; : : : ; un ) and v = (v1 ; : : : ; vn ) be two vectors in V = F n .
The scalar product of u and v is de ned as
X
n

u  v = u1 v1 + u2 v2 +  +u v
n n = u v:
k k

k =1
The scalar product satis es the following properties, whose veri cation
is left as an exercise.
1. u  v 2 F .
2. u  v = v  u.
3. u  (v + w) = u  v + u  w.
4. ( u)  v = (u  v ); u  ( v ) = (u  v ):
5. If v = O = (0; 0; : : : ; 0), then v  v = 0. Otherwise, v  v > 0.
A distance in a vector space
The size of a vector v = (v1 ; : : : ; vn ) in V is called the norm, which is
de ned as
jjvjj = v12 + v22 +    + vn2 = pv  v:
q
(10.2)
As usual, we de ne the distance between two vectors as the norm of their
di erence: jjv ujj. For F = R, this distance becomes the ordinary Eu-
clidean distance. Furthermore, for n = 1, the norm becomes the absolute
value.
There are other ways of de ning the norm of a vector, whence a distance
in F n . Speci cally, for any positive real number p we de ne the p-norm of
v as
jjvjjp = (jv1 jp + jv2 jp +    + jvn jp )1=p : (10.3)
Thus, the norm de ned in (10.2) is the 2-norm (p = 2). The case p = 1 is
also interesting. The 1-norm of a vector is the sum of the absolute value of
the coordinates.
jjvjj1 = jv1 j + jv2 j +    + jvn j:

Exercises
Exercise 10.1. Complete the proofs of the properties 1{6 of a vector
space, rst for n = 2, and then for arbitrary n.

10.3 Vectors with Maple

Arithmetic in vector spaces requires a speci c set of Maple functions, which


belong to the linear algebra library linalg. The easiest way to proceed
is to load this library explicitly, using the intrinsic function with
> with(linalg):
10.3. VECTORS WITH MAPLE 189

(With the semicolon, all functions being loaded are listed.) We begin con-
structing an unspeci ed 2-dimensional vector v = (v1 ; v2 ).
> v:=array(1..2);
v := array(1::2; [ ])
> v,whattype(v);
v; symbol
Unlike for other data types, the symbolic name of an array evaluates to
itself (a symbol). Full evaluation requires a call to the intrinsic function
evalm (evaluate to matrix)
> evalm(v);
[v1 v2 ]
> whattype(%);
array
In computational parlance, we say that the array's name represents a
pointer to the location in memory where the array information is stored.
The function evalm is used to fetch that information. (A procedure's name
has a similar status; see section 3.4.)
With the function op we can get some insight into the internal repre-
sentation of an array in Maple
> op(evalm(v));
 
1::2; 1 = v[1] ; 2 = v[2]
Thus, an array consists of a range, which speci es the dimension, and a
list, where each entry is assigned a value.
Next we construct a speci c vector in Z2
> v:=array([1,-4]);
v := [1 4]
The internal representation of v has now changed
> op(evalm(v));
1::2; [1 = 1; 2 = 4]
All components of an array may be accessed and assigned new values
> v[2];
4
> v[2]:=-3:evalm(v);
[1 3]
A vector can be multiplied by a scalar in a straightforward manner
> -2*v:%=evalm(%);
190 CHAPTER 10. VECTOR SPACES

2v = [ 2 6]
Likewise, vectors can be easily summed and subtracted
> u:=array([0,1]):
> z:=evalm(u+v);
z := [1 2]

> whattype(z),whattype(evalm(z));
symbol; array
In the last example, the new array z was generated without resorting to the
array command, by simply assigning to the name z a datum of the array
type. By contrast, the assignment
> w:=u+v:
assigns to w the algebraic expression u+v. Evaluation of z and w gives the
same result
> evalm(z),evalm(w);
[1 2]; [1 2]
but whereas z points to an array with a speci ed value, w points to the sum
of two variables which in turn point to arrays. Thus, if we change the value
of v
> v[1]:=99:
the value of w changes, but that of z does not
> evalm(z),evalm(w);
[1 2]; [99 2]
The scalar product | also called dot product | is supported by the
linalg function dotprod
> dotprod(u,v);
3
The p-norm of a vector (cf. equation (10.3)) is given by the function norm,
with p as a second argument
> norm(v,2);
p
10
> w:=array(1..3):norm(w,4);
 1=4
jw1 j4 + jw2 j4 + jw3 j4
Example 10.7. Let u = ( 2; 3; 1) 2 Z3. Consider the following recur-
sive sequence v0 ; v1 ; : : : of elements of Z3
v0 = (1; 0; 0); v +1 = f (v ) = 2 v + u; t  0:
t t t
10.4. MATRICES 191

We show that the rst 10 elements of this sequence are orthogonal to the
vector w = (0; 1; 3).
> u:=array([-2,-3,1]):
> w:=array([0,1,3]):
> v:=array([1,0,0]):
> f:=v->evalm(2*v+u):
> for t to 10 while dotprod(v,w) <> 0 do
> v:=f(v)
> od:
> t;
11
As usual, all the information is buried in the function f that performs the
recursion. There is no need of displaying any intermediate computation.
Failure of orthogonality would have resulted in a smaller value of t (make
sure you understand this).

10.4 Matrices

A matrix over T is a rectangular array of elements of a given set T


   2 
A= 2 3
5 7
B = c2 +cc + 1 5c1 c c 3 :

In the above example, A is a 2  2 matrix over Z, and B is a 2  3 matrix over


Z[c ] (the set of polynomials with integer coeÆcients in the indeterminate
c). An element aij of a matrix A is identi ed by two integers i and j ,
specifying its position within the array: the row and the column number.
In the above example, we have a21 = 5, and b13 = c2 3. To indicate
that aij are the elements of A, one writes A = (aij ).
Matrices, like numbers, are algebraic objects, which combine according
to two binary operations: addition and multiplication. To de ne these
operations one must consider matrices over a xed set T (usually a ring or
a eld ), and then impose constraints on the dimensions of such matrices.
The sum (subtraction) A  B of two matrices A and B is performed
componentwise, so it can be de ned only if the summands have the same
dimensions. Speci cally, if A = (ai;j ) and B = (bi;j ) are m  n matrices,
and C = (ci;j ) = A  B , we de ne
c =a
i;j ij b ij i = 1; : : : ; m; j = 1; : : : n:
The sum of matrices behaves much like the sum of, say, the integers. In
particular, it enjoys the commutative and associative properties; i.e., A +
B = B + A, and (A + B ) + C = A + (B + C ).
192 CHAPTER 10. VECTOR SPACES
The product C = A B is de ned when the column dimension of A is
the same as the row dimension of B . In this case let n be such common
dimension. The entry ci;j of C is de ned as the scalar product of the ith
row of A and the j th column of B
X
n

c = a 1 b1 + a 2 b2 +
ij i j i j  +a b in nj = a b :
ik kj

k =1
If A and B are square matrices, then both A B and B A are de ned, but
in general we have that A B 6= B A. Failure of commutativity results in a
very rich arithmetic.
Matrices may also represent certain functions , which assign to a vector
v in a vector space V1 the unique vector A v in another space V2 . (The
multiplication between a matrix and a vector turns out to be a special
case of multiplication between matrices.) The properties of matrices then
become properties of these functions.

10.5 Matrices with Maple

In Maple, matrices are represented as many-dimensional arrays


> A:=array([[0,1],[3,-1]]);
 
A := 03 1
1
The argument of the function array is a list consisting of two lists, repre-
senting the rst and second row of the array, respectively.
> A[2,1];
3
> -2*A:%=evalm(%);
 
0 2
2A =
6 2
> B:=array([[2,0],[1,1]]);
 
B := 21 01

> A+B:%=evalm(%);
 
A + B = 24 10
Matrix multiplication is non-commutative: if A and B are n by n ma-
trices, then AB 6= BA, in general. Maple supports the non-commutative
multiplication operator &*, which preserves the order of the operands.
> evalm(A&*B);
10.5. MATRICES WITH MAPLE 193
 
1 1
5 1
> evalm(B&*A);
 
0 2
3 0
> evalm(A*B);
Error, (in evalm/evaluate) use the &* operator for matrix/vector multipli-
cation
Maple knows that the commutative multiplication operator * is ambiguous
for matrices, and refuses to carry out the multiplication.
The following example illustrates further the di erences between com-
mutative and non-commutative multiplication, and clari es Maple's strat-
egy with expressions involving matrices.
> K:=array([[1,1],[1,0]]):
> L:=array([[2,1],[1,1]]):
The matrices K and L commute, that is, KL = LK .
> evalm(K&*L),evalm(L&*K);
   
3 2
2 1
; 32 21
Hence the commutator of K and L, given by KL LK , is equal to the 2
by 2 null matrix
> evalm(K&*L-L&*K);
 
0 0
0 0
However, if we instead use commutative multiplication, the result is quite
di erent (and wrong!)
> evalm(K*L-L*K);
0
> whattype(%%),whattype(%);
array; integer
Using commutative multiplication, we have obtained the integer 0 rather
than the 2 by 2 null matrix! Why? Also, why hasn't Maple complained |
as it did before | when we used commutative multiplication with matrices?
The reason is the following. Before accessing a matrix with evalm, Maple
carries out some automatic algebraic simpli cations, regarding K and L as
symbols. (This could result in massive eÆciency savings when dealing with
large arrays.) Thus, Maple rst transforms K*L into L*K, (or vice versa,
depending on the context), which is legitimate because * is commutative.
194 CHAPTER 10. VECTOR SPACES
Therefore, K*L-L*K evaluates to the integer 0, which is a valid argument
for evalm, that treats it as a 1  1 matrix.
As for vectors, matrices can be generated directly by assigning to a
variable the value of an evaluated matrix. In the next example, the value
of the variable C is A, which points to an array, while the variable D points
to a copy of the array A.
> C:=A:
> D:=evalm(A):
> A[1,1]:=22:
> evalm(C),evalm(D);
   
22 1
3 1
; 03 1
1
So changing A changes C but not D.
The library linalg supports a vast number of functions associated with
matrix arithmetic
> M:=array([[a,b],[c,d]]);
 
M := ac db
We begin with determinant and trace
> det(M),trace(M);
ad bc; a + d
Next we construct the characteristic polynomial of M , in the indeterminate
y
> charpoly(M,y);
y2 yd ya + ad bc
> collect(%,y);
y2 + ( | d{z a} ) y + ad bc
| {z }
Tr(M ) det(M )
We list some linalg functions applied to a matrix with integer coeÆcients

> A:=([[0,1],[3,-1]]):
> evalm(A),trace(A),det(A),rank(A),transpose(A),
> inverse(A),eigenvalues(A);

1 1p 1p
    1 1 
0 1 1
3 1
; 1; 3; 2; 01 3
1
; 3 3 ;
1 0
+ 13; 13
2 2 2 2

For more information about these functions, consult online documentation.


10.5. MATRICES WITH MAPLE 195

We consider some computation involving a 3 by 3 matrix over Z. First


we construct the matrix
> A:=array([[1,2,3],[4,5,6],[7,8,0]]);
2 3
1 2 3
A := 4 4 5 6 5
7 8 0
Next we verify that if f (x) is the characteristic polynomial of A, then f (A)
is the null matrix (this is the Hamilton-Cayley theorem, valid for any square
matrix)
> charpoly(A,z);
z 3 6 z 2 72 z 27
> subs(z=A,%);
A3 6 A2 72 A 27
> evalm(%);
2 3
0 0 0
40 0 05
0 0 0
This can be done directly as follows
> evalm(charpoly(A,A));
2 3
0 0 0
40 0 05
0 0 0
Maple multiplies any scalar by the identity matrix of the appropriate di-
mension before summing or subtracting it from a matrix
> evalm(%-2*x);
2 3
2x 0 0
4 0 2x 0 5
0 0 2x
We verify that the trace of A is the sum of its diagonal elements
> trace(A),add(A[k,k],k=1..3);
6; 6
Summing all elements of A requires a double sum
> add(add(A[i,j],i=1..3),j=1..3);
36
196 CHAPTER 10. VECTOR SPACES
Multiplying a matrix by a vector
Let the matrix A be as in the previous example.
> v:=array([1,0,-1]):
> evalm(A&*v);
[ 2 2 7]
The function evalm interprets vectors as column vectors (even though it
displays them as row vectors).
0 10 1 0 1
1 2 3 1 2
@4 5 6A @ 0 A = @ 2A:
7 8 0 1 7
This process can be iterated, to generate a recursive sequence of vectors
v0 = (1; 0; 1) v +1 = Av = f (v );
t t t t  0:
The Maple implementation is structurally identical to that of any other
recursive construction. All the information is buried in the de nition of the
function f
> f:=vct->evalm(A&*vct):
> to 4 do
> v:=f(v)
> od;
[ 2 2 7]
[15 24 30]
[27 0 297]
[864 1674 189]

Applying a function to all elements of an array


Let the matrix A be as in the previous example. We wish to square all
elements of A, that is, to apply a function to all elements of a composite
data type. This operation requires the use of the function map
> h:=y->y^2:
> map(h,A), map(z->z^2,A);
2 3 2 3
1 4 9 1 4 9
4 16 25 36 5 ; 4 16 25 36 5
49 64 0 49 64 0
The following example illustrates the use of map with elements of Z[x]2.
> v:=array([x+1,x^2]):
> map(h,v);
[(x + 1)2 x4 ]
10.5. MATRICES WITH MAPLE 197

> map(expand,%);
[x2 + 2x + 1 x4 ]
> x:=22:
> evalm(v);
[x + 1 x2 ]
> map(eval,v);
[23 484]
It should be noted that map acts on the entries of a matrix, even though
the latter are not its top-level operands (see chapter 6). With A as above,
we have
> op(evalm(A));

1::3; 1::3; [(1; 1) = 1; (1; 2) = 2; (1; 3) = 3; (2; 1) = 4; (2; 2) = 5; n


(2; 3) = 6; (3; 1) = 9; (3; 2) = 8; (3; 3) = 0]

> seq(whattype(x),x=[%]);
::; ::; list
We see that the operands of a matrix are two ranges specifying the dimen-
sions, and a list of equations de ning the entries. An array is a special case
of a more general construct called a table. See online documentation for
more information.
Exercises
Exercise 10.2. Load the linalg package.
(a) Consider the following vectors in Z3
u = (88; 2; 33) v = ( 7; 27; 1):
Compute their sum and their scalar product. Determine which one is the
longest, using the 2-norm.
(b) Construct the following matrices
0 1
1 2  
1 1 1
A = @2 0 A B= 4 6 2
:
3 1
Then modify one entry of A as follows (without rede ning the entire ma-
trix!) 0 1
1 2
A=@ 2 0 A (10.4)
5 1
198 CHAPTER 10. VECTOR SPACES
Then, using (10.4), compute BA, A B T , and AT + B (the superscript T
denotes the transpose of a matrix).
Exercise 10.3. Consider the recursive sequence of matrices
 
A0 = 21 11 A +1 = A2
t t A
t I2 ; t  0;
where I2 is the 2  2 identity matrix.
(a) Compute A5 , using a do-loop. Do not display any intermediate output.
(b) Compute and display the elements of the sequence of integers Dt =
trace(At ) for t = 1; : : : ; 5. No other output should be displayed.
Exercise 10.4. The commutator [A; B ] of two square matrices A and B
is de ned as
[A; B ] = AB BA:
(Note that if A and B were numbers, [A; B ] would be zero.)
(a) Construct a user-de ned function comm(A,B) whose value is [A; B ].
(b) Given the matrices
   
A = 01 1
1
B = 01 0
1

we consider the sequence of matrices


A = A ; B = B ; C = [A; B ] ;
n
n
n
n
n
n
n  1:
By generating a suÆcient number of elements of these sequences, convince
yourself that they are all periodic and hence determine their period.
Exercise 10.5. Let 0 1
1 1 0
M = @0 1 1A: (10.5)
1 0 0
(a) Construct a Maple function mu(M) for the function  which subtracts
1 from all entries of a matrix M ; e.g, if M is as above, then
0 1
0 0 1
(M ) = @ 1 0 0 A:
0 1 1
(b) Consider the recursive sequence of matrices
M0 = M M +1 = M + (M );
t t t t0
Generate the rst 5 elements of this sequence.
(c) By inspecting the result of the previous problem, conjecture the general
form of Mt , valid for t  0.
10.5. MATRICES WITH MAPLE 199

(d) Using Maple, prove by induction your conjecture of part (c). (This is
a computer-assisted proof.)
(e) Let M be as in (10.5). Consider the recursive sequence of vectors of Z3
v0 = (1; 0; 0) v +1 = M v + v0 ;
k k k  0:
Compute the smallest integer k for which the scalar product of vk and v0
exceeds 50.
Exercise 10.6. Let A and B be 3 by 3 matrices. Prove with Maple that

Det(AB ) = Det(A) Det(B ):


[Hint: practice rst with 2 by 2 matrices, until you are sure you can carry
out the calculation without displaying any intermediate output.]
Exercise 10.7. Let

0
s 0 0 24 1
A(s) = B 1 s 0 50 C
:
@
0 1 s 35 A
0 0 1 10 s

Determine the values of s for which A(s) is singular (non-invertible).


Chapter 11

Modular arithmetic 

Many arithmetical techniques involve operating with modular number sys-


tems, which are of importance in both theory and applications (data pro-
cessing, coding theory, cryptography, etc.). Modular arithmetic deals with
remainders of integer division. We have encountered these objects often, as
values of the function irem.
This section contains an informal introduction to modular arithmetic
with Maple. For further reading, see References [1, 2].

11.1 A modular system

We begin with arithmetic modulo the prime number 5. We consider the


following ve in nite sets of integers, called congruence classes modulo 5:
[0]5 = f :::; 20; 15; 10; 5; 0; 5; 10; 15; 20; : : : g
[1]5 = f :::; 19; 14; 9; 4; 1; 6; 11; 16; 21; : : : g
[2]5 = f :::; 18; 13; 8; 3; 2; 7; 12; 17; 22; : : : g (11.1)
[3]5 = f :::; 17; 12; 7; 2; 3; 8; 13; 18; 23; : : : g
[4]5 = f :::; 16; 11; 6; 1; 4; 9; 14; 19; 24; : : : g
By inspecting (11.1) we see that the rst set [0]5 is constructed starting
from the integer 0, and then adding to it all multiples of 5. Thus,
[0]5 = f ::: ; 0 3  5; 0 2  5; 0 1  5; 0+0  5; 0+1  5; 0+2  5; 0+3  5; : : : g:
Similarly
[1]5 = f ::: ; 1 3  5; 1 2  5; 1 1  5; 1+0  5; 1+1  5; 1+2  5; 1+3  5; : : : g;
etc., and in general, for k 2 Z we have
[k ]5 = f ::: ;k 3  5; k 2  5; k 1  5; k +0  5; k +1  5; k +2  5; k +3  5; : : : g:

201
202 CHAPTER 11. MODULAR ARITHMETIC


In the last equation, k is not restricted to the rst ve natural numbers.


In particular, the same congruence class may be represented by di erent
values of k . So, for instance, [1]5 , [6]5 , and [ 14]5 are the same class, as
easily veri ed.
From the above considerations, it follows that every integer in Z appears
in precisely one congruence class. Therefore, the union of these sets is the
whole of Z
[0]5 [ [1]5 [ [2]5 [ [3]5 [ [4]5 = Z;
and they are pairwise disjoint | they have empty intersection
[0]5 \ [1]5 = ; ; [0]5 \ [2]5 = ;; etc:
(We say that the 5 sets [0]5 ; [1]5 ; : : : ; [4]5 form a partition of Z.)
We de ne the following nite set
F5 = f[0]5 ; [1]5 ; [2]5 ; [3]5 ; [4]5 g:
Thus, F 5 consists of ve elements, each of which is an in nite set.
If two integers a and b belong to the same element of F 5 , we say that `a
is congruent to b modulo 5', and write
a  b (mod 5):
This expression is called a congruence (whence the name congruence classes ).
Thus,
5  0 (mod 5) 6  1 (mod 5) 2  3 (mod 5):
It is plain that two integers x and y belong to the same congruence class
precisely when they di er by a multiple of 5, that is, when x y gives
remainder zero when divided by 5. Thus, 19 and 21 belong to the same
class in F 5 , because their di erence 19 21 = 40 = ( 8)  5 is a multiple
of 5. So we have 19 21  0 (mod 5), and since 19  1 (mod 5), we
have [ 19]5 = [1]5 . Remainders of integer division are computed in Maple
with the intrinsic function irem (see section 2.4)
> irem(-19-21,5);
0
Example 11.1. Some congruences.
2 + 3  0 (mod 5) 2 4  3 (mod 5) 2  3  1 (mod 5):
To understand the middle congruence, note that 5  0 (mod 5), whence
40 45 4  1 (mod 5)
so 2 4  2 + 1  3 (mod 5).
11.1. A MODULAR SYSTEM 203

Determining membership to a class is somewhat delicate. Membership


is established by checking the remainder upon division by 5. However,
according to the de nition of remainder given in (2.11), two members of
a class will produce the same remainder only if they agree in sign. This
de nition is consistent with the behaviour of irem, whose value can be
positive as well as negative. Thus, 8, 13, and 7 belong to the same class
[3]5 , yet their respective remainders are not the same
> irem(8,5),irem(13,5),irem(-7,5);
3; 3; 2
(There is no contradiction here, since [3]5 = [ 2]5 .)
This problem is solved if we agree that we shall always use a non-
negative remainder. Maple has a speci c binary operator for modular
arithmetic, called mod, which returns the least non-negative remainder
of an integer division
> 8 mod 5,13 mod 5,-7 mod 5;
3; 3; 3
In the rest of this chapter, we shall always use mod.
All the above constructions and considerations can be generalized. We
replace 5 with an arbitrary prime number p, and de ne
Fp = f[0]p ; [1]p ; : : : ; [p 1]p g;
where the elements of F p are in nite sets de ned for every integer k as
follows
[k ]p = f :::; k 3  p; k 2  p; k 1  p; k +0  p; k +1  p; k +2  p; k +3  p; : : : g:
Again, the integer k is not restricted to the rst p natural numbers, so that
di erent values of k may correspond to the same class
[k ]p = [k + sp]p s 2Z :

The requirement that p be prime is essential, as we shall see.


Example 11.2. 2
21 and 10011 belong to the same congruence class
[89]101 of F 101 .
> 2^21 mod 101, -10011 mod 101;
89; 89
We construct a function to test the congruence x  y (mod m):
> AreCongruent:=(x::integer,y::integer,m::posint)
> -> evalb(x = y mod m):
> AreCongruent(2^21,-10011,101);
true

Note that the modulus m has data type posint, a positive integer.
204 CHAPTER 11. MODULAR ARITHMETIC


Exercises
Exercise 11.1. Construct the sets F 2 , F3 , and F 7 , as in (11.1).
Exercise 11.2. Verify the following congruences
6  5030497 (mod 503); 210 + 1013 29274  0 (mod 1000003):

Exercise 11.3. Determine the largest integer less than a million which
belongs to the class [777]1009 in F1009 .
Exercise 11.4. Prove that the union of the elements of F p is Z, and that
they are pairwise disjoint (they form a partition of Z.)

11.2 Arithmetic of equivalence classes

We are ready to de ne the four arithmetical operations for congruence


classes modulo a prime number. Addition, subtraction, and multiplication
derive naturally from the corresponding integer operations. More surprising
is the fact that division by a nonzero congruence class is also de ned, in
spite of the fact that the division of two integers does not yield an integer,
in general. As a result, arithmetic modulo a prime number will enjoy many
properties of rational arithmetic.
Addition, subtraction, and multiplication
Addition, subtraction, and multiplication can be performed without restric-
tions in Z. Using this property, we now de ne the corresponding operations
between congruence classes.
To sum two congruence classes [a]p and [b]p , we choose an arbitrary
element from each, and then compute their sum, which is an integer s. Since
the classes constituting Fp are disjoint, s must belong to precisely one class,
and the latter is de ned to be the sum of the two classes: [a]p + [b]p = [s]p .
It remains to be shown that this operation is well-de ned, that is, that
the result does not depend on the particular choice of a and b within the
respective classes. Thus, let a0 and b0 be two other elements of [a]p and
[b]p , respectively. Then for some integers k and l we have a0 = a + p k and
0 0 0
b = b + p l , so that a + b di ers from a + b by a multiple of p. But then
0 0
a + b and a + b belong to the same class, by de nition.

The same procedure is used to de ne subtraction and multiplication.


Thus, in F5 we have [4]5 + [3]5 = [2]5 . Indeed, choosing 6 2 [4]5 and
18 2 [3]5 , we nd that 6 + 18 = 12 2 [2]5 .
> -6+18 mod 5;
2
The integer 0 is the identity element of addition in Z: a + 0 = a, for any
integer a. It then follows that the class [0]p is the identity class of modular
addition, because we can always choose 0 as a representative element of [0]p .
11.2. ARITHMETIC OF EQUIVALENCE CLASSES 205

By the same token, the integer 1 is the identity element of multiplication in


Z: a  1 = a, for any integer a, so that [1]p is the identity class of modular
multiplication.
Division
Division cannot be performed unrestrictedly in Z, even if we exclude divi-
sion by zero. We approach this problem by attempting to construct the re-
ciprocal [1]p =[b]p of every nonzero element [b]p 2 F p . The quantity [1]p =[b]p
will be `that thing which, when multiplied by [b]p , gives [1]p ', called the
modular inverse of [b]p
[1]p
[b]p
 [b]p = [1]p : (11.2)

In order to determine [1]p =[b]p , we must solve the congruence x  b 


1 (mod p). Then 1=b  x (mod p). We do this for all nonzero elements
of F 5 .
x  1  1 (mod 5) =) x  1 (mod 5) =) [1]5 =[2]5 = [1]5
x  2  1 (mod 5) =) x  3 (mod 5) =) [1]5 =[2]5 = [3]5
x  3  1 (mod 5) =) x  2 (mod 5) =) [1]5 =[3]5 = [2]5
x  4  1 (mod 5) =) x  4 (mod 5) =) [1]5 =[4]5 = [4]5 :

Maple knows this


> seq(1/k mod 5, k=1..4);
1; 3; 2; 4
There is another way of looking at the construction of the modular
inverse. We know we cannot divide 1 by 2 in Z. Does this mean that we
cannot divide [1]5 by [2]5 in F 5 ? The procedure we have used to de ne
addition, subtraction, and multiplication made use of the corresponding
operations in Z performed on arbitrary elements of the operand classes. So
if we choose 1 from [1]5 and 2 from [2]5 , we are stuck, because 1=2 is not
in Z, and therefore it cannot be found in any class. However, if we instead
choose 6 as the representative element of [1]5 , then we can perform the
integer division: 6=2 = 3 2 [3]5 . We obtain the same result by selecting,
say, 21 2 [1]5 and 3 2 [2]5 , for 21=( 3) = 7 2 [3]5 . So it would seem
that division in F 5 can be derived consistently from division in Z, provided
we choose suitable (rather than arbitrary ) representative elements from the
relevant classes, that is, elements for which such division yields an integer
result.
It turns out that the above procedure works in general, due to the
following

Theorem 10 Let p be a prime number. Then, if b 6 0 (mod p), the con-


gruence x   1 (mod
b p) admits a unique solution modulo p.
206 CHAPTER 11. MODULAR ARITHMETIC


This theorem guarantees that for each class [b]p 6= [0]p we can nd a
unique class 1=[b]p , satisfying (11.2). But then for each [a]p and nonzero
[b]p , the quantity [a]p =[b]p is uniquely de ned, since
[a]p [1]
= [a]p  p :
[b]p [b]p
The construction of the inverse of b rests on Euclid's algorithm for the
greatest common divisor of two integers, according to which if b and p are
coprime, we can nd integers x and y such that x  b + y  p = 1, that is,
x  b  1 (mod p).

The existence of a multiplicative inverse ensures that for every prime p,


the set F p is a nite eld. In other words, in F p , like in Q , R, C , Q (x), etc.,
we can add, subtract, multiply, and divide, except division by zero. Thus,
for instance, any fraction with denominator coprime to p makes sense in Fp

> 7/5-41/4 mod 101;


77
It is important to note that the condition that p be prime is necessary
for the above construction. For instance, the inverse of a nonzero element
does not necessarily exist in the arithmetic modulo 6.
> 1/5 mod 6;
5
> 1/4 mod 6;
Error, the modular inverse does not exist

(Indeed, 4 is even, and so is any of its multiples, so that no multiple of


4 can be congruent to 1 modulo 6.) Modular arithmetic for a composite
modulus is very rich and interesting, but we shall not consider it here.

11.3 Some arithmetical constructions in Fp


In this section, we describe some standard constructions in a nite eld Fp :
the squares and higher powers, exponentiation and the logarithm, poly-
nomial arithmetic. (When no confusion can arise, we shall represent the
congruence class [a]p via the unique integer r  a (mod p), which lies in the
range 0; : : : ; p 1.)
Squares and higher powers
The function f := x 7! x2 maps the integers into the squares
f (Z) = f0; 1; 4; 9; 16; 25; 36; : : :g
11.3. SOME ARITHMETICAL CONSTRUCTIONS IN FP 207

and every nonzero square is the image under f of two distinct elements of
Z.
The squares in Z form a `thin set', in the sense that the probability that
an integer taken at random is a square tends to zero as the integer becomes
large. For instance, 40% of the integers less than 10 are squares, 10% of
the integers less than 100 are squares, and only some 3% of the integers
less than 1000 are squares.
The squares are also de ned in Fp , where the situation is quite di erent.
We begin with the case p = 7.
> F7:=f$0..6g;
f0 ; 1; 2; 3; 4; 5; 6g
To square the elements of F 7 , we make use of the operator mod
> f:=x->x^2 mod 7:
and to apply the function f to every element of F 7 we use the standard
library function map
> map(f,F7);
f0; 1; 2; 4g
This calculation shows that half of the 6 nonzero elements in F 7 are squares.
Speci cally, modulo 7, we have
1 2  6 2  1; 2 2  5 2  4; 3 2  4 2 = 2:
Next we count the squares in F 101
> f$0..100g:
> map(x->x^2 mod 101,%):
> nops(%)-1;
50
Thus, also in F101 , half of the nonzero elements are squares. This result is
true in general.

Theorem 11 Let p be an odd prime. Then half of the nonzero elements


of F p are squares.

The Maple number theory library numtheory features | among other


things | a rich set of functions for modular arithmetic. This library is
loaded with the command with
> with(numtheory):
(We have already seen this command in section 10.3.) Now we may freely
use all numtheory functions; for instance, to ascertain whether or not a is
a square modulo p, we use the function legendre(a,p), which returns +1
if a is a square in F p , 1 if a is not a square, and 0 if a is divisible by p.
208 CHAPTER 11. MODULAR ARITHMETIC


This function is (essentially) the characteristic function of the squares in


F p , which is known as the Legendre symbol.
> legendre(7,47);
1
The above result shows that 7 is a square modulo 47. To compute its least
non-negative square root, we use the function msqrt
> msqrt(7,47);
17
p
(The other value of 7 is then 17  47 17  30 (mod 47).)
If b is an integer greater than 1, then the function fb := n 7! bn will
map the elements of F p into the bth powers
Example 11.3. Find all the squares in F 29 which are not fourth powers.

> F29:=f$0..28g:
> f:=(x,b,p)->x^b mod p:
> map(f,F29,2,29):
> map(f,F29,4,29):
> %% minus %;
f4 ; 5; 6; 9; 13; 22; 28g

Exponentiation and logarithm


We consider the process of exponentiation in F p : x 7! bx (mod p), where
b is a xed integer. As an example, we consider the case p = 7 and b = 2.
We nd
20  1 (mod 7); 21  2 (mod 7); 22  4 (mod 7); 23  8  1 (mod 7)
whence 24  21 (mod 7), etc. Thus, the powers of 2 in F 7 are 1; 2, and 4;
that is, the exponential sequence n 7! [2n ]7 is periodic, with period 3.
In general, if a is not divisible by p, we call the (multiplicative) order
of a modulo p, to be the period of the sequence n 7! [an ]p . Since [1] = [a0 ]
belongs to the repeating part, the order of a modulo p can also be de ned as
the smallest positive integer n for which an  1 (mod p). The corresponding
Maple function is order(a,p)
> order(2,7)
3
However, the case b = 3 presents us with an interesting phenomenon. We
nd, modulo 7
30  1; 31  3; 32  2; 34  4; 35  5; 36  1:
11.3. SOME ARITHMETICAL CONSTRUCTIONS IN FP 209

Thus, all nonzero elements of F 7 can be expressed as some power of 3. It


turns out that this phenomenon is generic: in every nite eld there exists
at least one element g whose powers generate all nonzero eld elements.
Such g is called a primitive root modulo p. Alternatively, a primitive root
may be de ned as an integer g whose order is equal to p 1.
Example 11.4. The integer 2 is a primitive root modulo 11.
> seq(2^k mod 11, k=1..10);
2; 4; 8; 5; 10; 9; 7; 3; 6; 1
and 3 is a primitive root modulo 199
> for n while((3^n mod 199) > 1) do od:
> n;
198
The function primroot(p) of the numtheory library returns the smallest
positive primitive root modulo a prime p
> primroot(9973);
11
Let us double-check
> seq(order(a,9973),a=1..11);
1; 3324; 831; 1662; 3324; 3324; 3324; 1108; 831; 554; 9972
It can be shown that the order of an element is always a divisor of p 1
> map(x->9972 mod x,f%g);
f0g
The existence of a primitive root g modulo p implies that the congruence
g
y  a (mod p)
can always be solved for y , provided that a is nonzero. By analogy with the
complex case, we shall then call x the discrete logarithm of a to the base g ,
modulo p. The function mlog(a,g,p) computes such logarithm
> mlog(500,11,9973);
2085
> 11^2085 mod 9973;
500
Exponentiation in modular arithmetic is a well-known trapdoor function,
easy to do but very diÆcult to undo. In other words, the discrete logarithm
is a lot more time-consuming than its inverse, the exponentiation. We have
already encountered this phenomenon in regard to prime factorization (see
section 2.6).
210 CHAPTER 11. MODULAR ARITHMETIC


Polynomials
Since Fp is a eld, de ning polynomials with coeÆcient in F p presents no
conceptual diÆculty: one represents the coeÆcients as integers (or rationals
with denominator coprime to p). The operator mod will then reduce them
to the range 0; : : : ; p 1.
> 40*x^2-x/3-19 mod 13;
2
x +4x+7
For polynomial divisibility, Maple provides the inert functions Factor, Quo,
and Rem, to be used in conjunction with mod.
Let us consider the polynomial g (x) = x2 +1 in F 5 . Since 5  0 (mod 5)
and 6  1 (mod 5), we have
( ) = (x + 2) (x + 3) = x2 + 5x + 6  x2 + 1 (mod 5):
g x

We see that g (x) factors in F 5 as (x + 2)(x +p3), much in the same way
as it factors in C as (x + i)(x i), where i = 1 is the imaginary unit.
Therefore, 2  3 and 3  2 are the two square roots of 1 in F 5 .
> Fg:=p->Factor(x^2+1) mod p:
> Fg(5);
(x + 2) (x + 3)
Writing it all out in detail, we have
( ) = [1]5 x2 + [1]5 = (x
g x [2]5 ) (x [3]5 ); g ([2]5 ) = g ([3]5 ) = [0]5 ;
that is, g(x) has two distinct roots in F 5
Let us look into the factorization of x2 + 1 in F p , for other values of p
> seq(Fg(ithprime(k)),k=1..6);

(x + 1)2 ; x2 + 1; (x + 3) (x + 2) ; x2 + 1; x2 + 1; (x + 8) (x + 5)

> map(whattype,[%]);
[^; +; ; +; +; ]
Three types of factorizations occur, corresponding to x2 + 1 having one
double root (data type ^), two distinct roots (data type ), or no roots at
all (data type +) modulo p. It turns out that these are the only possibilities.
We explore this phenomenon for a large set of primes
> data:=map(whattype,[seq(Fg(ithprime(k)),k=1..1000)]):
Now the variable data contains the data type of the factored polynomials,
which in this case is preferable to storing the polynomials themselves. We
count the occurrence of each of the three types, using the function select
in conjunction with nops
11.3. SOME ARITHMETICAL CONSTRUCTIONS IN FP 211

> seq(nops(select((x,y)->evalb(x=y),data,y)),y=[`^`,`*`,`+`]);
1; 495; 504
Thus, the double root occurs only once (for the prime p = 2), while the
other two cases occur with roughly equal probability.

Exercises
Exercise 11.5. Determine the cubes in F101 .
Exercise 11.6. Show that all elements of F 29 have at least one cube root.
Exercise 11.7. Determine all primitive roots modulo 101.
Exercise 11.8. Convince yourself that for every positive integer k the
polynomial x2 + 1 has two distinct roots modulo 5k . That is, there exist
integers ak and bk such that x2 + 1  (x ak )(x bk ) (mod 5k ). Represent
ak and bk to the base p: what do you observe as k becomes large?

Exercise 11.9. By considering the factorization of the polynomial x


3 2
in F p for a large set of primes p, provide evidence that the probability that
2 has three cube roots modulo p is 1/6.
Chapter 12

Some abstract structures


In this chapter, we present the axiomatic de nition of some abstract struc-
tures that have been exempli ed throughout the course.

12.1 The axioms of arithmetic


We list the fundamental properties of the integers (called axioms ) from
which most other properties can be derived. Let x, y, and z be integers.
Then
I x + y and x  y are in Z. closure
II x + y = y + x; x  y = y  x. commutativity
III (x + y) + z = x + (y + z ); associativity
(x  y)  z = x  (y  z ).
IV x + 0 = x; x  1 = x. identity elements
V x  (y + z ) = x  y + x  z . distributivity
VI For each x 2 Z there exists x 2 Z inverse of addition
such that x + ( x) = 0.
VII If x  y = x  z and x 6= 0 then y = z cancellation

Note that the integers 0 and 1 enjoy a special status, in that addition
by 0 and multiplication by 1 do not alter the elements of Z. The properties
IV should indeed be taken as the de nition of the identity elements of
addition and multiplication, respectively. Any set satisfying these axioms
(with 0 and 1 possibly replaced by two elements of the set) will have many
properties in common with Z. Sets of this type are called integral domains:
they are the integers' closest relatives.
213
214 CHAPTER 12. SOME ABSTRACT STRUCTURES


12.2 Metric spaces


A metric space is a set where we can measure the distance between any two
elements. Speci cally, a metric space is a set X equipped with a function
(x; y) de ned for all x; y 2 X which has the properties:
I (x; y) is real and non-negative.
II (x; y) = 0 if and only if x = y.
III (x; y) = (y; x). symmetry
IV (x; z )  (x; y) + (y; z ). triangle inequality
Example 12.1. The set C with distance (x; y) = jx yj is a metric
space. The subsets N ; Z; Q , and R of C inherit from C the distance ,
whence the structure of metric spaces.
Example 12.2. Let 2 (n) be the set of binary sequences of n elements:
x = (x1 ; x2 ; : : : ; xn ), xk 2 f0; 1g. We de ne

(x; y) =
X jx
n
k yk j:
k=1

Then (x; y) is an integer between 0 and n. Because (x; y) is a nite sum


of non-negative terms, it is zero only when all summands are zero, that
is, when x = y. Properties III and IV follow from the corresponding
properties of the function jx yj. Thus, 2 (n) with the distance  is a
metric space.

12.3 Rings and elds


A set R is called a ring if two binary operations are de ned in R, called
sum (+) and multiplication (), satisfying the following conditions for all
elements of R
I a + y = y + a. commutativity of sum
II (a + y) + z = a + (y + z ); associativity
(a  y)  z = a  (y  z ).
III a  (y + z ) = a  y + a  z ; distributivity
(a + y)  z = a  z + y  z .
IV For all a; b 2 R there exists x 2 R injectivity of sum
such that a + x = b.
Letting b = a in IV, we obtain the identity element x = 0 of addition.
Letting b = 0, we obtain the additive inverse x = a of a.
Note that multiplication need not be commutative. If the commutative
law holds for multiplication, i.e., if a  b = b  a, the ring is said to be
commutative. If an element 1 exists such that 1  a = a  1 = a for all a, then
R is said to be a ring with unity.
12.4. VECTOR SPACES 215
Example 12.3. The set of even integers
2Z = f : : : ; 4; 2; 0 ; 2 ; 4 ; : : : g
is a commutative ring without unity.
Example 12.4. The subset of C constituted by all complex numbers with
integer real and imaginary parts forms a ring, called the ring of Gaussian
integers, denoted by Q [i]
p
Q [i] = fx + iy j x; y 2 Z; i = 1g:
Replacing the integer 1 under p the square root with an integer D not a
square, we obtain the ring Q [ D].
A commutative ring F is called a eld if there is always a solution x to
the equation a  x = b, for all a 6= 0 and b in F . (The ring F is assumed not
to consist of the single element 0.) Letting b = a, we obtain the identity
element x = 1 of multiplication. Letting b = 1, we obtain the multiplicative
inverse x = a 1 of a.

12.4 Vector spaces


Let F be a eld (with elements ; ; : : :). A set V (with elements u; v; w; : : :)
is a vector space over F if any two elements of V can be added, and any
element of V can be multiplied by elements of F , in such a way that the
following properties are satis ed
I u + v and v lie in V . closure
II u + v = v + u. commutativity
III (u + v) + w = u + (v + w). associativity
IV There exists O 2 V such that additive identity
O + u = u + O.
V ( 1)u 2 V is such that inverse of sum
u + ( 1)u = O.
VI (u + v) = u + v, distributivity of sum
( + )u = u + u.
VII ( )v = ( v). distribut. of scalar mult.
VIII 1 v = v. identity of scalar mult.
In VIII above, 1 is the multiplicative identity of the eld.
Bibliography
[1] N. L. Biggs,
Discrete mathematics, Clarendon Press, Oxford (1994).
[2] H. Davenport, The higher arithmetic , Cambridge University Press,
Cambridge (1999).
[3] M. Liebeck,A concise introduction to pure mathematics,Chapman &
Hall/CRC, London (2000).
[4] P. Ribenboim, The new book of prime number records , Springer-
Verlag, New York (1995).
[5] J. Silverman,
A friendly introduction to number theory,Prentice-Hall,
Englewood Cli s, New Jersey (1996).
[6]The New Scientist guide to chaos, N. Hall, Editor, Penguin Books,
London (1991).

217
Index
3x + 1 conjecture, 176 data type
exprseq, 62
abs, 19, 28, 30, 37, 105, 108 oat, 97
add, see sum fraction, 27
arccos, arcsin, arctan, 108 integer, 27
associativity, 8, 9, 44, 187, 191, list, 64
213{215 posint, 203
procedure, 51
binomial range, 62
binomial, 153, 164 set, 45
coeÆcient, 78 string, 66
theorem, 80 symbol, 52
de Moivre's theorem, 108
Cassini identity, 85 degree, 128
ceil, 108, 109 denom, 27, 28, 37, 54, 93, 109, 178
commutativity diff, 2
commutator, 193 digits
non-commutative multiplica- Digits, 90
tion operator, 192 number of, 37, 38, 109
of addition, 187, 191, 213{ of rationals, see rational num-
215 bers
of logical operators, 47 pseudo-random, 100
of multiplication, 213{215 Diophantus of Alexandria, 24
complex conjugate, 104 discrete logarithm, 209
computer-assisted proof, 76, 158, distance
174, 199 in a metric space, 214
conjugate, 105 in a vector space, 188
constants in C , 104
p, 2, 89 in Q , 27
2, see square root in R, 96
e (Napier's constant), 109, 179 in Z, 7
continued fractions, 31 triangle inequality, 7, 28, 105
convert, 142 distributivity, 215
cos, cosh, 108 ditto variables, see variables
cot, coth, 108 divisors
csc, csch, 108 greatest common, 22, 24
219
220 INDEX

number of, 33 rational, 26


pairs of, 20 real, 96
prime, 33, 125 floor, 108, 109
proper, 20 for, see do-loops
twin, 21 functions
do-loops bijective, 49, 78
do, 163 characteristic, 52{55, 60, 69,
for, 164, 165 149
in, 169 Euler totient, 124, 159
loop control variable, 165 factorial, 1, 77, 78, 80, 84,
while, 169, 170, 175, 178 109
for divisibility, 23
error gamma, 109
absolute, 109 injective, 49
relative, 109 piecewise-de ned, 177
syntactical, 8 surjective, 49
Euclid, 32 trapdoor, see trapdoor func-
Euclid's algorithm, 206 tions
eval, 52 user-de ned, 50
evalb, 18, 19, 24, 28, 53, 56, 80,
121, 122, 134, 150 GAMMA, 108, 110
evalc, 105, 108 gcd, 133
evalf, 2, 90, 91, 98, 101, 105,
108, 110, 121, 178 Hamilton-Cayley theorem, 195
evalm, 189{194, 196, 197
exp, 108, 109 I, 105
expand, 2, 34, 81, 125, 130, 133, if, 53{55, 156, 177, 178
138, 139, 151, 169 ifactor, see factorization
expressions igcd, 23, 37, 62, 63, 68, 123, 133,
algebraic, 14 156, 166
arithmetical, 8 ilcm, 23, 37, 72, 133
logical, 46 Im, 105
nested, 13, 167 imaginary unit, 102, 210
relational, 18 in, see do-loops
int, 3
factorization integral domain, 213
Factor, 210 intersect, 46
factor, 37, 121, 133, 141, 151 iquo, 23, 30, 37, 54, 63, 93, 109,
ifactor, 33, 34, 37, 93, 125, 133, 174
133, 151, 169 third argument, 38, 94
Fibonacci numbers, 84 irem, 23, 24, 28, 37, 48, 53{56,
eld, 214 70, 73, 93, 133, 174, 182,
Cartesian product of, 186 202
complex, 103 third argument, 38, 94
nite, 206 isqrt, see square root
INDEX 221
kernelopts, 10 mul, see product
multiplicative order, 208
lcm, 133
lcoeff, 128 nops, 45, 120, 122, 124, 174, 175,
least common multiple, 23, 131 180, 181, 210
Legendre symbol, 208 normal, 138, 141
length, 37, 38, 116 NULL, 62, 167{169, 174, 178
libraries numer, 27, 28, 37, 54, 93, 109, 178
linalg, 188 numtheory, see libraries
charpoly, 194, 195
det, 194 op, 98, 113{115, 121, 123, 125,
dotprod, 190 156, 189, 197
eigenvalues, 194 operators
inverse, 194 arithmetical, 8
norm, 190 arrow, 51
rank, 194 assignment, 14
trace, 194 logical, 46{48
transpose, 194 non-commutative multiplica-
numtheory, 207 tion, 192
legendre, 208 relational, 18
mlog, 209 selection, 115, 175
msqrt, 208 sequence $, 62, 175
order, 208 set, 46
phi, 159 option, 182
primroot, 209
standard library, 37 partition, 202
limit, 2 Pascal's triangle, 79, 164
linalg, see libraries permutations, 78, 80
log, log10, log[b], 108 Pi, 2, 90, 111
piecewise, 178
map, 56, 120, 121, 179, 196, 207 plots
optional arguments, 62 multiple, 72
max, 108, 109 of a complex sequence, 106
mediant, see rational numbers of a real function, 111
member, 47, 175, 176 of a sequence, 65
Mersenne numbers, 35 options
largest known prime, 35 linestyle, 72
Lucas' test, 35 scaling, 107, 124
mersenne, 36 title, 66
primes, 10, 35, 41 plot, 3, 64, 65, 68, 70, 111
metric space, 214 pointer, 51, 189
min, 108, 120 polynomials
minus, 46, 47, 124, 175, 208 in several indeterminates, 135
mod, 105, 203{210 irreducible, 132
modular inverse, 205 monic, 132
222 INDEX

roots of, 137, 210 rem, 133, 134


primes, 32 remainder of division
gaps between, 65 for integers, 22, 38, 48, 67,
isprime, 34, 35, 48, 54, 56, 69{71, 73, 203
61, 120, 122, 150 divisibility testing, 24
ithprime, 36, 37, 61, 65, 66, for polynomials, 132, 134
73, 170, 182 divisibility testing, 134
largest known, see Mersenne remove, 121
numbers ring, 214
largest known twins, 41 of Gaussian integers, 215
nextprime, 36, 37, 180
prevprime, 36, 37 scalar product, 187
primality test, 34 sec, sech, 108
twin, 41, 50, 122 select, 120{123, 181, 210
primitive root, 209 seq, 61, 62, 65, 68, 74, 80, 94, 97,
print, 166, 170 115, 119{121, 123, 134
proc, 179{182 sequences
product aÆne, 70
double, 155 chaotic, 168
inert (Product), 153 doubly-in nite, 59
numerical (mul), 149{151 eventually periodic, 91, 173
symbolic (product), 152 Farey, 73
proof by contradiction, 102, 123 fast-growing, 87, 88
pseudo-random numbers, 100 Fibonacci, 84
Pythagorean triples, 24 linear, 70
modulation of, 71
Quo, 210 notation, 59
quo, 133 of digits, 89
quotient of division of polynomials, 134
for integers, 20, 22, 38, 67, of sets, 73
69{71 periodic, 67, 68, 71, 102, 107,
for polynomials, 132, 134 198, 208
random, 73
rand, 101 recursive, 82, 94
rational numbers sets
Archimedean property, 28 cardinality, 40
digits of, 89, 92{94 di erence, 43
fractional part, 28 empty, 40
integer part, 28 intersection, 43
mediant, 30, 95, 178 power set, 42
midpoint, 30 subset, 42
rational approximation, 99, 178 union, 43
reduced form, 27 sign, 108
Re, 105 simplify, 110, 131, 138, 140, 141
Rem, 210 sin, sinh, 108
INDEX 223
solve, 3
sort, 174
square root p
digits of 2, 101p
irrationality of 2, 102
isqrt, 37, 63
Newton's method, 99
sqrt, 2, 101, 109, 178
Stirling's formula, 109
substitutions
sequential, 17
simultaneous, 17, 83
subs, 16, 17, 52, 117, 141,
153
subsop, 116, 118
sum
double, 154, 155
inert (Sum), 153
numerical (add), 149{151, 156,
174, 195
symbolic (sum), 2, 152
tan, tanh, 108
time, 181
trapdoor functions, 34, 209
triangle inequality, see distance
triangular numbers, 100
union, 46, 176
value, 154
variables
ditto, 12, 15, 164
global, 134
local, 180
vector space, 215
visible points, 122, 156
whattype, 27, 45, 51, 52, 62, 64,
97, 113, 118, 151, 189,
190, 197, 210
while, see do-loops
with, 188, 207

You might also like