318 7 2MB
English Pages 520 Year 2006
C++ for Mathematicians An Introduction for Students and Professionals
Edward Scheinerman
Cover photograph: Ira Scheinerman Cover design concept: Jonah Scheinerman
Published in 2006 by Chapman & Hall/CRC Taylor & Francis Group 6000 Broken Sound Parkway NW, Suite 300 Boca Raton, FL 33487-2742 © 2006 by Taylor & Francis Group, LLC Chapman & Hall/CRC is an imprint of Taylor & Francis Group No claim to original U.S. Government works Printed in the United States of America on acid-free paper 10 9 8 7 6 5 4 3 2 1 International Standard Book Number-10: 1-58488-584-X (Softcover) International Standard Book Number-13: 978-0978-1-58488-584-9 (Softcover) 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. No part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC) 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged. 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 Taylor & Francis Web site at http://www.taylorandfrancis.com Taylor & Francis Group is the Academic Division of Informa plc.
and the CRC Press Web site at http://www.crcpress.com
In loving memory of Pauline and of Arnold
Contents
List of Programs
xiii
List of Figures
xvii
Preface
xix
I
Procedures
1
1 The Basics 1.1 What is C++? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Hello C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 3 4 8
2 Numbers 2.1 The integer types . . . . . . . . . . . . . . . . . . 2.2 The real number types . . . . . . . . . . . . . . . 2.3 The bool and char types . . . . . . . . . . . . . 2.4 Checking the size and capacity of the different types 2.5 Standard operations . . . . . . . . . . . . . . . . . 2.6 Comparisons and Boolean operations . . . . . . . 2.7 Complex numbers . . . . . . . . . . . . . . . . . . 2.8 Naming variables . . . . . . . . . . . . . . . . . . 2.9 Exercises . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
11 11 14 14 15 18 22 23 27 28
3 Greatest Common Divisor 3.1 The problem . . . . . . . . . . . . . . . . . . . 3.2 A first approach . . . . . . . . . . . . . . . . . 3.3 Euclid’s method . . . . . . . . . . . . . . . . . 3.4 Looping with for, while, and do . . . . . . 3.5 An exhaustive approach to the GCD problem . 3.6 Extended gcd, call by reference, and overloading 3.7 Exercises . . . . . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
31 31 31 37 41 43 45 49
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
53 53 54 57 60
4 Random Numbers 4.1 Pseudo random number generation . . . . . . 4.2 Uniform random values . . . . . . . . . . . . 4.3 More on pseudo random number generation . 4.4 A Monte Carlo program for the GCD problem
. . . .
. . . . .
. . . .
v
vi
C++ for Mathematicians 4.5 4.6
Normal random values . . . . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5 Arrays 5.1 Euler’s totient . . . . . . . . . . . . . . . . . . 5.2 Array fundamentals . . . . . . . . . . . . . . . 5.3 A procedure to factor integers . . . . . . . . . 5.4 A procedure to calculate Euler’s totient . . . . . 5.5 The Sieve of Eratosthenes: new and delete[] 5.6 A faster totient . . . . . . . . . . . . . . . . . 5.7 Computing pn for large n . . . . . . . . . . . . 5.8 The answer . . . . . . . . . . . . . . . . . . . 5.9 Exercises . . . . . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
II Objects
61 63 67 67 69 71 76 78 83 85 87 88
91
6 Points in the Plane 6.1 Data and methods . . . . . . . . . . . . . . 6.2 Declaring the Point class . . . . . . . . . 6.3 Data hiding . . . . . . . . . . . . . . . . . 6.4 Constructors . . . . . . . . . . . . . . . . . 6.5 Assignment and conversion . . . . . . . . . 6.6 Methods . . . . . . . . . . . . . . . . . . . 6.7 Procedures using arguments of type Point 6.8 Operators . . . . . . . . . . . . . . . . . . 6.9 Exercises . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
93 93 94 97 99 100 101 103 104 112
7 Pythagorean Triples 7.1 Generating Pythagorean triples . . . . . . . . 7.2 Designing a primitive Pythagorean triple class 7.3 Implementation of the PTriple class . . . . 7.4 Finding and sorting the triples . . . . . . . . 7.5 Exercises . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
115 115 116 117 121 125
8 Containers 8.1 Sets . . . . . . . . . . . . . . . . . . . 8.2 Set iterators . . . . . . . . . . . . . . . 8.3 Multisets . . . . . . . . . . . . . . . . 8.4 Adjustable arrays via the vector class 8.5 Ordered pairs . . . . . . . . . . . . . . 8.6 Maps . . . . . . . . . . . . . . . . . . 8.7 Lists, stacks, and assorted queues . . . . 8.7.1 Lists . . . . . . . . . . . . . . . 8.7.2 Stacks . . . . . . . . . . . . . . 8.7.3 Queues . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
127 127 130 133 134 138 139 144 144 148 148
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
vii
Table of Contents
8.8
8.7.4 Deques . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 8.7.5 Priority queues . . . . . . . . . . . . . . . . . . . . . . . 150 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
9 Modular Arithmetic 9.1 Designing the Mod type . . . . . . . . . . . . . . . . . 9.2 The code . . . . . . . . . . . . . . . . . . . . . . . . . 9.3 The default modulus: Static class variables and methods 9.4 Constructors and get/set methods . . . . . . . . . . . . 9.5 Comparison operators . . . . . . . . . . . . . . . . . . 9.6 Arithmetic operators . . . . . . . . . . . . . . . . . . 9.7 Writing Mod objects to output streams . . . . . . . . . 9.8 A main to demonstrate the Mod class . . . . . . . . . 9.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
157 157 158 163 167 167 169 172 172 174
10 The Projective Plane 10.1 Introduction to the projective plane, RP2 . . . . . . 10.2 Designing the classes PPoint and PLine . . . . 10.3 Inheritance . . . . . . . . . . . . . . . . . . . . . 10.4 Protected class members . . . . . . . . . . . . . . 10.5 Class and file organization for PPoint and PLine 10.6 The parent class PObject . . . . . . . . . . . . . 10.7 The classes PPoint and PLine . . . . . . . . . . 10.8 Discovering and repairing a bug . . . . . . . . . . 10.9 Pappus revisited . . . . . . . . . . . . . . . . . . . 10.10 Exercises . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
177 177 178 181 184 186 187 195 200 207 211
. . . . . . . . . . . .
215 215 217 218 218 220 223 224 225 225 225 229 232
11 Permutations 11.1 Ulam’s problem . . . . . . . . . . . . . . . . . . . 11.2 Designing the Permutation class . . . . . . . . 11.2.1 Data . . . . . . . . . . . . . . . . . . . . . 11.2.2 Constructors and destructors . . . . . . . . 11.2.3 Copy and assign . . . . . . . . . . . . . . . 11.2.4 Basic inspection and modification methods . 11.2.5 Permutation operations . . . . . . . . . . . 11.2.6 Comparison operators . . . . . . . . . . . . 11.2.7 Output . . . . . . . . . . . . . . . . . . . . 11.2.8 The code file Permutation.c . . . . . . 11.3 Finding monotone subsequences . . . . . . . . . . 11.4 Exercises . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
viii
C++ for Mathematicians
12 Polynomials 12.1 Procedure templates . . . . . . . . . . . . . . . . 12.2 Class templates . . . . . . . . . . . . . . . . . . 12.2.1 Using class templates . . . . . . . . . . . 12.2.2 Creating class templates . . . . . . . . . . 12.3 The Polynomial class template . . . . . . . . 12.3.1 Data . . . . . . . . . . . . . . . . . . . . 12.3.2 Constructors . . . . . . . . . . . . . . . . 12.3.3 Get and set methods . . . . . . . . . . . . 12.3.4 Function methods . . . . . . . . . . . . . 12.3.5 Equality . . . . . . . . . . . . . . . . . . 12.3.6 Arithmetic . . . . . . . . . . . . . . . . . 12.3.7 Output to the screen . . . . . . . . . . . . 12.3.8 GCD . . . . . . . . . . . . . . . . . . . . 12.3.9 The code . . . . . . . . . . . . . . . . . . 12.4 The GCD problem revisited . . . . . . . . . . . . 12.5 Working in binary . . . . . . . . . . . . . . . . . 12.5.1 Signed versus unsigned integers . . . . . 12.5.2 Bit operations . . . . . . . . . . . . . . . 12.5.3 The bitset class template . . . . . . . 12.5.4 Class templates with non-type arguments . 12.6 Exercises . . . . . . . . . . . . . . . . . . . . .
III
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
Topics
13 Using Other Packages 13.1 Arbitrary precision arithmetic: The GMP package 13.2 Linear algebra . . . . . . . . . . . . . . . . . . . 13.2.1 Two-dimensional arrays in C++ . . . . . . 13.2.2 The TNT and JAMA packages . . . . . . 13.2.3 The newmat package . . . . . . . . . . . 13.3 Other packages . . . . . . . . . . . . . . . . . . 13.4 Exercises . . . . . . . . . . . . . . . . . . . . .
235 235 238 238 239 242 243 243 244 245 246 246 247 247 247 254 258 258 259 260 263 264
267 . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
269 269 273 273 274 282 286 287
14 Strings, Input/Output, and Visualization 14.1 Character arrays . . . . . . . . . . . . . . . . . . . . . 14.2 The string class . . . . . . . . . . . . . . . . . . . 14.2.1 Initialization . . . . . . . . . . . . . . . . . . . 14.2.2 Fundamental operations . . . . . . . . . . . . . 14.2.3 Searching . . . . . . . . . . . . . . . . . . . . 14.2.4 Converting between string and char* types 14.3 Command line arguments . . . . . . . . . . . . . . . . 14.4 Reading and writing data in files . . . . . . . . . . . . 14.4.1 Opening files for input/output . . . . . . . . . . 14.4.2 Reading and writing . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
289 289 291 291 292 295 297 297 300 300 303
. . . . . . .
. . . . . . .
ix
Table of Contents
14.5 14.6
14.7 14.8
14.9
14.4.3 Detecting the end of an input file . . . . . . . . . . . . . . 14.4.4 Other methods for input . . . . . . . . . . . . . . . . . . . String streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.6.1 Setting precision . . . . . . . . . . . . . . . . . . . . . . 14.6.2 Showing all digits . . . . . . . . . . . . . . . . . . . . . . 14.6.3 Setting the width . . . . . . . . . . . . . . . . . . . . . . 14.6.4 Other manipulators . . . . . . . . . . . . . . . . . . . . . A class to parse files . . . . . . . . . . . . . . . . . . . . . . . . Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.8.1 Introducing and installing the plotutils package . . . . 14.8.2 Drawing with plotutils—a first example . . . . . . . 14.8.3 Pascal’s triangle modulo two . . . . . . . . . . . . . . . . 14.8.4 Tracing the motion of a point moving randomly in a triangle 14.8.5 Drawing Paley graphs . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15 Odds and Ends 15.1 The switch statement . . . . . . . . . . . . . . . . . 15.2 Labels and the goto statement . . . . . . . . . . . . . 15.3 Exception handling . . . . . . . . . . . . . . . . . . . 15.3.1 The basics of try, throw, and catch . . . . 15.3.2 Other features of the exception-handling system 15.4 Friends . . . . . . . . . . . . . . . . . . . . . . . . . 15.5 Other ways to create types . . . . . . . . . . . . . . . 15.5.1 Structures . . . . . . . . . . . . . . . . . . . . 15.5.2 Enumerations . . . . . . . . . . . . . . . . . . 15.5.3 Unions . . . . . . . . . . . . . . . . . . . . . . 15.5.4 Using typedef . . . . . . . . . . . . . . . . 15.6 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . 15.6.1 Pointer basics . . . . . . . . . . . . . . . . . . 15.6.2 Dereferencing . . . . . . . . . . . . . . . . . . 15.6.3 Arrays and pointer arithmetic . . . . . . . . . . 15.6.4 new and delete revisited . . . . . . . . . . . 15.6.5 Why use pointers? . . . . . . . . . . . . . . . . 15.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . .
IV
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
Appendices
A Your C++ Computing Environment A.1 Programming with a command window and a text editor A.1.1 What you need and how to get it (for free) . . . A.1.2 Editing program files . . . . . . . . . . . . . . A.1.3 Compiling and running your program . . . . . A.1.4 Compiler options . . . . . . . . . . . . . . . .
304 305 307 308 309 309 310 311 311 315 316 317 322 324 326 330 333 333 336 338 338 342 344 347 347 348 348 349 350 350 351 353 355 356 358
361
. . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
363 363 364 365 366 368
x
C++ for Mathematicians
A.2
A.3
A.1.5 Introduction to make . . . . . . . . . . . . . . . . Programming with an integrated development environment A.2.1 Visual C++ for Windows . . . . . . . . . . . . . . A.2.2 Xcode for Macintosh OS X . . . . . . . . . . . . . General advice on debugging . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
370 372 373 376 378
B Documentation with Doxygen B.1 Doxygen comments . . . . . . . . . . . . . . . B.1.1 Documenting files . . . . . . . . . . . . B.1.2 Documenting procedures . . . . . . . . B.1.3 Documenting classes, data, and methods B.2 Using Doxygen . . . . . . . . . . . . . . . . . B.2.1 Configuring Doxygen . . . . . . . . . . B.2.2 Running Doxygen . . . . . . . . . . . . B.2.3 More features . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
381 381 382 382 383 386 386 389 389
C C++ Reference C.1 Variables and types . . . . . . . . . . . . . . C.1.1 Fundamental types . . . . . . . . . . C.1.2 Standard classes/templates . . . . . . C.1.3 Declaring variables . . . . . . . . . . C.1.4 Static variables and scope . . . . . . . C.1.5 Constants and the keyword const . . C.1.6 Arrays . . . . . . . . . . . . . . . . . C.2 Operations . . . . . . . . . . . . . . . . . . . C.2.1 Assignment . . . . . . . . . . . . . . C.2.2 Arithmetic . . . . . . . . . . . . . . . C.2.3 Comparison operators . . . . . . . . . C.2.4 Logical operators . . . . . . . . . . . C.2.5 Bit operators . . . . . . . . . . . . . . C.2.6 Potpourri . . . . . . . . . . . . . . . C.3 Control statements . . . . . . . . . . . . . . C.3.1 if-else . . . . . . . . . . . . . . . C.3.2 Looping: for, while, and do . . . . C.3.3 switch . . . . . . . . . . . . . . . . C.3.4 goto . . . . . . . . . . . . . . . . . C.3.5 Exceptions . . . . . . . . . . . . . . . C.4 Procedures . . . . . . . . . . . . . . . . . . . C.4.1 File organization . . . . . . . . . . . C.4.2 Call by value versus call by reference C.4.3 Array (and pointer) arguments . . . . C.4.4 Default values for arguments . . . . . C.4.5 Templates . . . . . . . . . . . . . . . C.4.6 inline procedures . . . . . . . . . . C.5 Classes . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
391 391 391 391 392 392 393 393 394 394 394 394 394 395 395 396 396 396 397 398 398 398 399 399 400 400 400 401 401
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
xi
Table of Contents
C.6
C.5.1 Overview and file organization C.5.2 Constructors and destructors . C.5.3 Operators . . . . . . . . . . . C.5.4 Copy and assign . . . . . . . . C.5.5 static data and methods . . C.5.6 this . . . . . . . . . . . . . C.5.7 Friends . . . . . . . . . . . . C.5.8 Class templates . . . . . . . . C.5.9 Inheritance . . . . . . . . . . . Standard functions . . . . . . . . . . C.6.1 Mathematical functions . . . . C.6.2 Mathematical constants . . . . C.6.3 Character procedures . . . . . C.6.4 Other useful functions . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
401 402 403 404 405 406 406 407 407 408 408 411 411 413
D Answers
415
Index
487
Programs
1.1 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 4.1 4.2 4.3 4.4 4.5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 6.1 6.2
Poem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introducing the int type. . . . . . . . . . . . . . . . . . . . . A program to illustrate integer overflow. . . . . . . . . . . . . . A program to show the sizes of the fundamental data types. . . . Extreme values of various data types. . . . . . . . . . . . . . . A program to explore C++’s mod operation. . . . . . . . . . . . A program to calculate eπ and π e . . . . . . . . . . . . . . . . . Handling complex numbers. . . . . . . . . . . . . . . . . . . . A header file, complexx.h. . . . . . . . . . . . . . . . . . . The header file gcd.h. . . . . . . . . . . . . . . . . . . . . . . Revised documentation for gcd in the header file gcd.h. . . . Beginning of the file gcd.cc. . . . . . . . . . . . . . . . . . . Ensuring a and b are nonnegative in gcd.cc. . . . . . . . . . The last part of the gcd.cc program. . . . . . . . . . . . . . . A program to test the gcd procedure. . . . . . . . . . . . . . . A recursive procedure for gcd. . . . . . . . . . . . . . . . . . An iterative procedure for gcd. . . . . . . . . . . . . . . . . . A program to calculate pn . . . . . . . . . . . . . . . . . . . . . A slightly better program to calculate pn . . . . . . . . . . . . . Code for the extended gcd procedure. . . . . . . . . . . . . . . Header file uniform.h. . . . . . . . . . . . . . . . . . . . . Definitions of the unif procedures in uniform.cc. . . . . . The problem with lower-order bits in an LCG. . . . . . . . . . . A Monte Carlo approach to calculating pn . . . . . . . . . . . . A program to generate Gaussian random values. . . . . . . . . . Header file for first version of factor. . . . . . . . . . . . . . Source file for first version of factor. . . . . . . . . . . . . . A main to test the factor procedure. . . . . . . . . . . . . . Header file for the totient procedure. . . . . . . . . . . . . . The code for the totient procedure. . . . . . . . . . . . . . . The header file sieve.h. . . . . . . . . . . . . . . . . . . . . The sieve procedure. . . . . . . . . . . . . . . . . . . . . . . A program to test the sieve procedure. . . . . . . . . . . . . . A faster totient procedure that employs a table of primes. . . A program to calculate pn for n equal to one million. . . . . . . Header file Point.h for the Point class (condensed version). Code for the Point class methods and procedures. . . . . . . .
. 5 . 11 . 13 . 15 . 17 . 19 . 21 . 23 . 24 . 32 . 34 . 34 . 35 . 35 . 37 . 38 . 40 . 43 . 44 . 48 . 54 . 56 . 58 . 60 . 63 . 73 . 74 . 75 . 76 . 77 . 79 . 81 . 82 . 84 . 85 . 95 . 109
xiii
xiv
C++ for Mathematicians 6.3 7.1 7.2 7.3 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 9.1 9.2 9.3 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 10.13 11.1 11.2 11.3 11.4 11.5 12.1 12.2 12.3 12.4 12.5 12.6 12.7 13.1 13.2 13.3 13.4 13.5
A program to check the Point class. . . . . . . . . . . . . . . . Header file for the PTriple class. . . . . . . . . . . . . . . . . Program file for the PTriple class. . . . . . . . . . . . . . . . . A program to find Pythagorean triples. . . . . . . . . . . . . . . . A program to find Pythagorean triples using sets. . . . . . . . . . A program to demonstrate the use of multiset. . . . . . . . . . The Sieve of Eratosthenes revisiting using vector classes. . . . A program to illustrate the use of maps. . . . . . . . . . . . . . . A procedure that remembers values it has already calculated. . . . A program to demonstrate the use of lists. . . . . . . . . . . . A program to illustrate the deque container. . . . . . . . . . . . Demonstrating the use of the priority queue container. . . . Header file for the Mod class, Mod.h. . . . . . . . . . . . . . . . Source file for the Mod class, Mod.cc. . . . . . . . . . . . . . . A program to illustrate the use of the Mod class. . . . . . . . . . . A program to illustrate inheritance. . . . . . . . . . . . . . . . . Using protected members of a class. . . . . . . . . . . . . . . Header file for all projective geometry classes, Projective.h. Header file for the PObject class (version 1). . . . . . . . . . . Program file for the PObject class (version 1). . . . . . . . . . Header file for the PPoint class. . . . . . . . . . . . . . . . . . Program file for the PPoint class. . . . . . . . . . . . . . . . . Header file for the PLine class. . . . . . . . . . . . . . . . . . . Program file for the PLine class. . . . . . . . . . . . . . . . . . A main to test the RP2 classes. . . . . . . . . . . . . . . . . . . Header file for the PObject class (version 2). . . . . . . . . . . Program file for the PObject class (version 2). . . . . . . . . . A program to illustrate Pappus’s theorem and its dual. . . . . . . Header file for Permutation class, Permutation.h. . . . . Program file for Permutation class. . . . . . . . . . . . . . . Header file monotone.h. . . . . . . . . . . . . . . . . . . . . . Finding longest monotone subsequences. . . . . . . . . . . . . . A program to illustrate Ulam’s problem. . . . . . . . . . . . . . . Header file for the max of three template. . . . . . . . . . . . The template for the mycomplex classes. . . . . . . . . . . . . Revised version of mycomplex. . . . . . . . . . . . . . . . . . Header file for the Polynomial class template. . . . . . . . . . Header file long2poly.h. . . . . . . . . . . . . . . . . . . . . Code file for the long2poly procedure. . . . . . . . . . . . . . Main program for the GCD revisited problem. . . . . . . . . . . . A program to illustrate the use of the GMP package. . . . . . . . Assignment versus copying in the TNT package. . . . . . . . . . A template to calculate the trace of an Array2D matrix. . . . . . Using TNT and JAMA on a Hilbert matrix. . . . . . . . . . . . . Using newmat on a Hilbert matrix. . . . . . . . . . . . . . . . .
110 117 120 122 129 133 137 141 143 146 150 151 159 162 172 181 184 186 191 192 197 198 198 199 200 202 203 207 217 226 230 230 231 236 240 241 247 255 256 256 271 275 277 280 285
xv
Programs 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 14.10 14.11 14.12 14.13 14.14 15.1 15.2 15.3 15.4 15.5 A.1 B.1 B.2
A program to illustrate the sorting of string values. . . . . Accessing command line arguments. . . . . . . . . . . . . . . Calculating the gcd of command line arguments. . . . . . . . A program the processes files specified on the command line. A program that illustrates writing data to a file. . . . . . . . . A program that sums the integer values it finds in a file. . . . . A program to illustrate the use of string streams. . . . . . . . Header file for the LineParser class. . . . . . . . . . . . . Program file for the LineParser class. . . . . . . . . . . . A program to demonstrate the use of the LineParser class. A program to draw the symbol ⊗. . . . . . . . . . . . . . . . Visualizing Pascal’s triangle mod 2. . . . . . . . . . . . . . . A program to plot points in a triangle by a random method. . . A program to draw Paley graphs. . . . . . . . . . . . . . . . . A program to illustrate the switch statement. . . . . . . . . Basic exception handling. . . . . . . . . . . . . . . . . . . . Catching exceptions thrown by other procedures. . . . . . . . A new Point.h header with friend procedures. . . . . . . Illustrating pointer dereferencing. . . . . . . . . . . . . . . . A basic Makefile. . . . . . . . . . . . . . . . . . . . . . . Documenting a procedure for Doxygen. . . . . . . . . . . . . Documenting a class and its members for Doxygen. . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
294 298 299 302 303 304 308 313 313 314 321 322 325 328 334 339 340 345 351 370 382 384
Figures
1.1 5.1 5.2 10.1 10.2 10.3 10.4 14.1 14.2 14.3 14.4 14.5 B.1 B.2
PDP-8 front panel switches. . . . . . . . . . . . . A flowchart for the factoring algorithm. . . . . . . Illustrating the Sieve of Eratosthenes algorithm. . . An illustration of Pappus’s theorem. . . . . . . . . An illustration of the dual of Pappus’s theorem. . . Hierarchy of the PObject classes. . . . . . . . . An illustration of Desargues’ Theorem. . . . . . . Illustrating a null-terminated character array. . . . The symbol ⊗ drawn by Program 14.11. . . . . . Visualizing Pascal’s triangle modulo 2. . . . . . . An image based on a random process in a triangle. The Paley graph on 17 vertices. . . . . . . . . . . Doxygen GUI window. . . . . . . . . . . . . . . . Doxygen configuration panel. . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
3 73 79 179 179 186 213 290 322 324 327 330 387 387
xvii
Preface
To my fellow students of mathematics This book is written for you. This is the book that I wish someone had written for me. This is a book that introduces the C++ language for people who are interested in solving mathematical problems. There is a dizzying selection of books on C++ written for a wide array of audiences. Visit your favorite bookseller and you can find C++ books for finance, numerics, computer security, game programming, embedded controllers, graphical user interfaces, network protocols, data and file structures, engineering, scientific computing, digital signal processing, simulation, neural nets, artists, virtual machine design, graphics, computational physics, cellular automata, cryptography, Web agents, business, aerospace and flight simulation, music and MIDI instruments, mobile phones, language translation, computer-aided design, speech recognition, database development, computer architecture, photographic imaging, fuzzy logic, hardware control, rigid body kinematics, real programmers, and—of course—for dummies. We assume that none of the above applies to you. We approach C++ from the point of view of solving mathematical problems. We organize our discussion around the mathematics and bring in the relevant C++ ideas as we need them.
Why C++? There is a plethora of computer tools available to the mathematical scientist. Many of these are suited for specific purposes. For example, if you need to perform extensive calculations in support of a number theory problem, the Pari package is perfect. There is a variety of commercial software packages that are excellent for mathematical work including Maple, MATLAB, and Mathematica to name but a few. For many mathematical problems, these systems work perfectly. However, for problems that require extensive computation the speed of a compiled language such as C++ cannot be beat. A C++ program can work through billions of examples faster than most other computing choices. The length of time it takes to solve a problem on a computer begins not when you run your program; it begins when you first start to write your program. The objectoriented nature of C++ enables you to create correct programs quickly. Furthermore, there is an extensive collection of C++ programs freely available on the Web that can be customized and used for your purposes (we discuss a few of these in Chapter 13). In addition, C++ is available for free on most computer systems. See Appendix A for more information about different versions of C++ for various computing envi-
xix
xx
C++ for Mathematicians
ronments (Windows, UNIX, Macintosh).
What can my computer do for me? Although the utility of computers in the sciences and engineering is unquestionable, it is not as clear that a computer is useful for mathematics. However, there are several arenas in which a computer can be a mathematician’s best friend. • Symbolic computation. Mathematical work often requires us to fuss with formidable formulas and solve elaborate equations. Computer algebra systems such as Maple and Mathematica are extremely useful for such work. • Visualization. The computer can draw precise pictures and diagrams; often these images provide key insights to understanding problems. • Examples and counterexamples. The computer can run through millions of examples and try myriad possibilities. It is a laboratory in which to perform experiments to see if ideas work and for discovering patterns. • Contribution to proof. Sometimes, parts of proofs can be relegated to the computer for checking. A celebrated example of this is the 1970s-era proof of the Four Color Theorem by Appel and Haken. More recently, Tom Hales’s announced proof of the Kepler Conjecture required extensive computation. I have used the computer in all these ways in my research. Allow me to share an amusing anecdote in which the computer contributed to the proof of a theorem. I was working with two colleagues on a problem in discrete mathematics. We knew that we could complete one portion of the proof if we could find a graph with certain specific properties. We carefully wrote down these criteria on a blackboard and set out to find the elusive graph. Although we tried to create the required graph by hand, each example we tried took us several minutes to check. We realized that the criteria could be checked mechanically and so we wrote a program to generate graphs at random until one with the needed properties was found. The first time we ran the program, it asked us for the number of vertices. Because we were unsuccessful with small examples, we typed in 50. Nearly instantly we were rewarded when the computer printed out a few screenfuls of data specifying the graph. Heartened by this (but not wanting to tangle with such a large graph), we ran the program again asking for a graph with only 20 vertices. Again, we were greeted with near instant success. We started to draw the graph on the blackboard, but it was a nasty random mess (no surprise—our program was designed to examine random graphs one after another). One more run. Shall we be optimistic? Certain this would not work, we ran the program again for graphs on 5 vertices. Success! The graph was actually quite simple and we had a good laugh over how we found our answer.
Preface
xxi
Using this book This book is ideal either for self-study or as a text for a semester-long course in computer programming (with an emphasis on mathematics). It is important that undergraduate mathematics majors know how to use the computer effectively. This is a skill that will serve them well whether for applied scientific/engineering/financial work, or as a means for forming and testing conjectures in pure research. We explain how to use C++ from the ground up, however, some experience in writing programs in any language will help. The reader does not need extensive experience in programming. Nor is a deep mathematical background needed to read this book. Our examples are drawn from standard mathematical topics such as Pythagorean triples [integers (a, b, c) such that a2 + b2 = c2 ] and polynomials. Whether you are reading this book on your own or in conjunction with a course, the most effective way to learn is to do. Every chapter ends with a collection of exercises; do them all. This is important for two reasons. First and foremost, mastery of any skill requires practice, and learning C++ is no exception. Second, additional ideas and subtle points are explored in the exercises. To assist you, we include complete solutions to nearly every exercise in Appendix D.
Organization We organize our discussion around mathematical themes. For example, Chapters 3 to 5 cover many central ideas in C++ (from how to write procedures to dynamic allocation of arrays), but a single mathematical problem runs throughout, taking us from Euclid to Riemann. The main body of the book is divided into three parts: Procedures, Objects, and Topics. Procedures focuses on writing C++ procedures (often called functions by our computer science colleagues, but we have a different meaning for that word). Objects introduces the object-oriented method of programming. If you want to solve a problem that involves permutations, Chapter 11 shows how C++ can handle these structures nearly as comfortably as it handles integers. Topics discusses how to use freely available packages that you can use in your programs, more advanced input/output, visualization, and selected special features of the C++ language. Four appendices provide (A) an overview of computing systems (including Integrated Development Environments), (B) the use of the Doxygen documentation system, (C) a quick reference to the C++ language and supporting libraries, and (D) answers to nearly every exercise.
No pointers! (almost) The C++ concepts covered in this book are not exhaustive. There are aspects of the language that are relevant only to computer scientists and software engineers. For example, C++ provides a number of exotic casting operators (such as reinterpret_cast) that are not of interest to mathematicians; we omit those. Nei-
xxii
C++ for Mathematicians
ther multiple inheritance nor pure virtual functions are for us. We do not explain how to make C++ programs work with other languages such as assembly language. We don’t create our own namespaces. For these and other C++ topics that are useful to large software engineering projects, please refer to any of several excellent, comprehensive C++ reference books. One topic that we touch only gently is the use of pointers. Mostly, we do not need them. We successfully avoid this confusing (and errorprone) concept through the use of call-by-reference and STL container classes. A mathematician shouldn’t be worrying about exotic data structures such as red–black trees; we just want to insert and delete elements in a set and not to worry about how the computer manages the set. There are, however, a few instances where a rudimentary understanding of pointers is necessary. • The name of a C++ array is a pointer to its first element. We need to understand this when we pass an array to a procedure and when we dynamically allocate storage for an array. • Sometimes an object needs to refer to itself (e.g., when a method such as operator+= returns the value of the object). In these instances, the this pointer is useful. We do not provide an extensive discussion of string processing (but do cover the basics in Chapter 14). As mathematicians, we are interested in getting data into our programs and results out of them; we are not going to construct word processors. We omit the exotic and focus on those aspects that make C++ a formidable weapon in the mathematician’s arsenal. With your brain and this book, your problem doesn’t stand a chance. Enjoy!
Additional resources The CD-ROM that comes with this book includes the code for all the numbered programs (see the List of Programs on page xiii). The programs are free for you to use under the terms of the GNU General Purpose License. (See the CD-ROM for details.) The disk also includes solutions to some of the lengthier exercises. Please visit the Web site for this book www.ams.jhu.edu/˜ers/cpp4m/ where we maintain a list of errata and submissions for Exercise 1.1.5.
Acknowledgments Many thanks to my editor Sunil Nair and his helpful staff at Taylor & Francis/CRC Press. They helped with everything from LATEX issues to copy editing to securing permissions. Promit Roy is an undergraduate computer science major at Johns Hopkins University. He read through the entire manuscript checking for accuracy and compatibility
Preface
xxiii
with Microsoft Visual Studio. In addition, he prepared the MS Visual Studio project files for the accompanying CD-ROM. Thank you, Promit! At various points in this book I recommend that the reader consult a “friendly computer science colleague.” I am fortunate to have such a colleague. Thank you, Joanne Houlahan for your help (and patience) with getting me unstuck from computer woes. I greatly appreciate my department chair, Daniel Naiman, for his support and encouragement for this project. It gives me great joy to acknowledge the contributions of my father, Ira, and my son Jonah to the front cover. Grandpa took the cover photo and grandson provided the design concept. Most important, thank you to my wife, Amy, and our children, Jonah, Naomi, Danny, and Rachel, for the world of love and happiness I share with them. Ed Scheinerman Baltimore May 24, 2006
Part I
Procedures
Chapter 1 The Basics
1.1
What is C++?
C++ is a computer programming language. Computers are electronic information-processing machines. Data and programs in these machines are saved, moved, and transformed in the form of electrical voltages. These electrical voltages can be interpreted as a zeros and ones. The zeros and ones can be aggregated and interpreted as words, numbers, images, sounds, and so on. Long ago, information—be it data or programs—could be entered into the
Figure 1.1: A PDP-8 computer with front panel switches for entering instructions and data. (Image courtesy of the Computer Museum at the University of Stuttgart. Photograph by Klemens Krause.)
3
4
C++ for Mathematicians
computer by manipulating switches on the front of the machine. Today, there are better methods. Computer programming languages convert text into the requisite binary instructions. C++ is a compiled language. This means that before the program is run, it is first translated into a form that the machine can use directly. The C++ files (and a typical project contains several) are called the source files. You create the source files by typing them using a program called a text editor. The translation of the source files into a program proceeds in two phases. First, the individual source files are translated by a program called the compiler into socalled object files. Next, a second program, called a linker (or loader) combines the individual object files into an executable file, that is, a program you can execute (run). The precise manner in which is all this is done (source file creation/editing, compiling, linking, and execution) varies among different computing platforms. In Appendix A we discuss how this is done for some common computing platforms (Windows, Macintosh, UNIX). Ideally, you have already done some programming, say in C, and so you are familiar with the general flow of this process. If not, your best option is to have someone show you how to perform these basic steps. In theory, your computer contains documentation that explains all this. However, such documentation is most useful to someone who already knows what to do, but needs reminders on specifics. With the help of Appendix A, a friendly neighbor knowledgeable in programming, and documentation (if any) you will get past this first, often frustrating hurdle. Rest assured that the process is simple once you know what it is. The hard part is knowing just which menu to select or what command to type to set the process in motion. For example, on many computers you translate your C++ files into a working program with the single command: g++ *.cc
and then run your program by typing this: ./a.out
If you are using an integrated development environment (also called an IDE) compiling your C++ files may be as simple as clicking on a button that says “build” and then running your program by clicking on a button that says “run”.
1.2
Hello C++
To begin we need to write a program; it’s time to present our first example. It is traditional to start with a program that does nothing more than type the words Hello, world onto the computer screen. Instead, we opt for a bit of (bad) poetry.
The Basics
5
Program 1.1: The classic “Hello, world” program updated for the mathematics world. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include using namespace std; /** * A simple program for demonstrating the basics of a C++ project. * * It does a good job of demonstrating C++ fundamentals, but a * terrible job with the poetry. */ int main() { cout