large number.pdf
TRANSCRIPT
-
8/10/2019 Large number.pdf
1/102
THE LARGE INTEGER
CASE STUDYIN C++
Advanced Placement ProgramTHE COLLEGE BOARD
AP Computer Science
-
8/10/2019 Large number.pdf
2/102
NATIONAL OFFICE
M id dle States
Mar y Alice G illigan
Suit e 410, 3440 Ma rket S tr eetPhiladelphia, PA 19104-3338
(215) 387-7600
Midwest
B ob McDonough/P a ula H erron
Suit e 401, 1800 Sh erma n Avenue
Evanston, IL 60201-3715
(847) 866-1700
New E ngland
Fred Wetzel
470 Tott en P ond Roa dWaltham, MA 02154-1982
(617) 890-9150
South
G eoffrey F reer /Tom N ew
Suite 250, 2970 Clairmont Road
Atlanta, GA 30329-1639
(404) 636-9465
COLLEGE BOARD REGIONAL OFFICES
Southwest
P a ul William son/Fr a nces B rown /Mondy R a ibon
Suite 1050, 98 Sa n J a cinto B oulevardAust in, TX 78701-4039
(512) 472-0231
West
Lindy D a ters/Cla ire P elton
Suite 480, 2099 G a tew a y P lace
Sa n J ose, C A 95110-1017
(408) 452-1400
Canada (AP Program On ly)
G eorge Ew onus
212-1755 Spr ingfield Roa dKelowna, B.C., Canada V1Y 5V5
(250) 861-9050
Wade Curry P hilip Arbolino Cha rlotte G il l Frederick Wright
45 Columb us Avenue New York, N Y 10023-6992 (212) 713-8000
This booklet w as produced by E ducational Testing Service (ETS), which d evelops an d a dministers t heexaminat ions of the Advanced Placement P rogram for the College Board. The College Board an d
Educat ional Testing Service (ETS) are dedicated t o the principle of equal opportunit y, and their programs,services, and employment policies a re guided by t hat principle.
Founded in 1900, the College Board is a not-for-profi t educat ional association tha t supports academic preparat ion and t ran sit ion to highereducation for students around the w orld through the ongoing collaborat ion of i ts member schools, colleges, universit ies, educational
systems, and organizations. In al l of i ts activit ies, the Board promotes equity through universal access to high standards of teaching andlearning a nd sufficient finan cial resources so that every student ha s the opportunity to succeed in college and work. The College Board
champions by means of superior research; curricular d evelopment; a ssessment; guidan ce, placement, and admission informa tion;professional development; forums; policy an alysis; a nd public outreach educational excellence for a l l student s.
Copyright 1997 by College Entra nce Examina tion Boar d an d Edu cational Testing Service. All rights reserved.
College Board, Advanced P lacement P rogram, AP, an d th e acorn logo are registeredtrademarks of the C ollege Entra nce Examinat ion Board.
THE COLLEGE BOARD: EDUCATIONAL EXCELLENCE FOR ALL STUDENTS
-
8/10/2019 Large number.pdf
3/102
Advanced PlacementComputer Science
The Large IntegerCase Study in C++
A Manual for Students
Th e AP Pr ogram wi shes to acknowl edge and to thank
Owen A str achan of Duk e U ni ver sit y for developi ng th is case stu dy
and th e accompanyi ng docum ent ati on.
Pl ease note that r epr oducti on of thi s docum ent is perm i tt ed f or face-to-face teachi ng pu r poses onl y.
-
8/10/2019 Large number.pdf
4/102
This is t he premiere posting of t he Adva nced P lacement Computer ScienceLa rge Integer Ca se Study in C+ + . Comments a nd/or suggestions regarding
this ma terial should be sent to Ga il Cha pman a t gchapma [email protected].
For more informa tion a bout AP C omput er Science, see theAP Comput er Science section of College Boa rd On line (CB O):
ht t p://w w w.collegeboa rd .org /a p/comput er-scien ce/ht ml/indx001.h t ml
College Board On line also ha s a publicat ions store wh ere you can pla ceorders for College B oard a nd AP publicat ions. The AP Aisle of the
College Boar d Online store ca n be found a t:
ht t p://cbw eb2.collegeboa rd .org/sh opping /
-
8/10/2019 Large number.pdf
5/102
CONTENTS
LARGE INTEGER CASE STUDY IN C++
Int roduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1P roblem Sta tement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Descr ipt ion of the Calcula tor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Specifica t ion of BigInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Solut ion Narra t ive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Design Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Overal l S tructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Error Ha ndl ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Forma l S pecifica tions for BigIntFunct ions . . . . . . . . . . . . . . . . . . . . . . . . . . 11Da ta Structure Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Choosing a data representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13A new structure for the program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
IMPLEMENTATION OF THE LARGE INTEGER PACKAGE
B uild ing the Scaf folding: Fundamenta l and I/O Funct ions . . . . . . . . . . . . 18Testing the Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Refining Our Implementa tion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Compa rison Opera tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Implementing Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Testing Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34The Subtra ction Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Multiplica tion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Multiplica tion by a n int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
-
8/10/2019 Large number.pdf
6/102
Alia sing: A New P roblem Arises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Fixing operator *= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44St udy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
APPENDICES
Appendix A: The Ca lcula tor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Appendix B : The H ea der File bigint.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Appendix C Cont ents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Appendix C: bigint.cpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Appendix D: bigint.cppw i th Al ias ing P r ob lems . . . . . . . . . . . . . . . . . . . . . 64
Appendix E: Test P rogra ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Appendix F: Sa mple Exa mina tion Questions . . . . . . . . . . . . . . . . . . . . . . . 69Appendix G: Answers to Stu dy Questions . . . . . . . . . . . . . . . . . . . . . . . . . . 78
AP PUBLICATIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
-
8/10/2019 Large number.pdf
7/1021
Large Integer Case Study in C++
for
AP Computer Science
Introduction
This document describes th e process of producing a solution t o a
progra mming problem. I t is intended t o provide a n opport unity for
a pprent iceship learn ing. The na rra tive is writ ten a s instruction from an
expert t o a n a pprent ice, a nd st udy qu estions represent pla ces wh ere th e
expert w ould sa y, Now you go try th is. Idea lly, you w ill get involved in
th e solution of th e problem a nd be a ble to compare your own d esign a nd
development decisions w ith th ose of th e a uth ors.
This case st udy includes progra ms t ha t solve the problem, together
with a na rra tive of how the progra ms a re designed a nd implemented. I t
describes an d justifies choices ma de during th e problem solution. It a lso
cont a ins exercises t o guide your st udy of the problem a nd it s solution.
The progra m code described here is ava ilable via t he In ternet (see the
U RL below ).
As you rea d the case study a nd th e code, you ma y ha ve questions
regarding C+ + a nd how i t is used. In some cases the questions ma y not be
a nsw ered in t his document . You should consult a tea cher, a book, or t hewebsite with supporting ma terials and explana tions a t :
ht t p://w w w.collegeboa rd .org/a p/comput er-scien ce/ht ml/indx001.ht ml .
Problem Statement
Arithmetic opera tions a re fundam enta l in computing a nd progra mming. In
ma ny progra mming environments t he largest va lue of an integer va r iable
is much too sma ll to represent lar ge qua nt ities such a s th e populat ion of
th e world, the U .S. na tiona l debt, t he number of occurrences of the letter
e in Melv illes M oby Dick, and ma ny other qua nti t ies . Encryption a nd
verifica tion methods are other applica tions tha t use extr emely la rge
int egers. Alth ough a 16 bit int eger is limited (norma lly) t o positive
va lues less tha n 32,768, even a 32 bit integer ha s a ma ximum va lue of
2,147,483,647 w hich is st ill too sma ll to represent some of the q ua nt ities
ment ioned a bove. Using floa ting point (real) num bers isnt a lwa ys a
rea sona ble option since comput er a rith metic wit h such num bers is inexact.
-
8/10/2019 Large number.pdf
8/1022
We wil l construct a softwa re packa ge tha t permits st ora ge and
ma nipulat ion of la rge (i.e., grea ter th a n INT_MAX1) integer values. Well
tr y to produce a tool tha t migh t be used in a va riety of environment s wh ere
such values a re needed. Once th is package ha s been built, it sh ould be
possible to use th e code, uncha nged, in a ny progra mm ing cont ext. S omeexamples of applications include:
A ca lcu la t or tha t hand les ver y la r ge in teger va lues .
A program t hat invest igates proper t ies of numbers including
Fibona cci sequences, la rge factorial va lues, and prime numbers.
A pr ogr am used for encr ypt ing messages and t r ansact ions tha t
ta ke place over the Int ernet.
A bank ing pr ogr am tha t uses la r ge account ba l ances and
transactions. A spr eadsheet pr ogr am tha t uses la r ge va lues .
Wel l implement t he softwa re pa cka ge as a C+ + class na med BigInt.
To test t he cla ss w ell use a progra m t ha t w orks a s a simple, line-oriented
calcula tor. The first version of the cla ss w ill use int va lues ra th er tha n
lar ge integer values. As we design a nd implement t he class BigIntw ell be
a ble to use th e sam e ca lcula tor progra m t o test t he implementa tion since
a ll int eraction wit h t he class is t hrough public member functions w hich will
not cha nge a l though t he priva te implementa tion w ill change.
Description of the Calculator
The calculat or w ill implement a ddition, subtra ction, a nd m ultiplica tion. An
expression like 25 *32 + 5 is evaluat ed using the calculat or progra m by
entering n umbers a nd opera tors one per line. After ea ch value is ent ered,
th e current va lue of the expression is displayed a nd used a s th e left
opera nd for t he next opera tor. Ent ry of an " = " terminat es the progra m. A
sa mple run is shown below. Notice th a t in its current form it a ccepts C+ +
int va lues ra ther tha n BigIntva lues. The code for t his ca lculat or progra m is
given in Append ix A.
Enter value: 5000
> 5000
Enter operator (+ - * (= to quit)): *
1 The consta nt INT_MAXis defined in the hea der file .
-
8/10/2019 Large number.pdf
9/1023
Enter value: 3
> 15000
Enter operator (+ - *(= to quit)): +
Enter value: 17
> 15017
Enter operator (+ - *(= to quit)): *
Enter value: 4
> -5468
Enter operator (+ - *(= to quit)): =
The l imita tions of ar i th metic in C+ + a re shown in the sam ple run
w here t he va lue of 15017 *4 is given a s 5468 ra th er th a n t he correct
va lue of 60,0682. This kin d of error is called overflow; the ma ximum
integer va lue ha s been exceeded a nd th e result is incorrect. This calculat or
progra m performs only t hree a rithm etic operat ions. A fully functiona lcalcula tor w ould include add itiona l opera tions including d ivision,
exponent iat ion, etc., and a meth od for eva lua ting expressions other
th a n t he line-oriented a pproa ch.
Study Questions
1. Suppose you w a nt to add una ry operat ions (i .e. , ones requir ing only one
operand ) to the calcula tor. For example, w e might a dd " M" t o indica te
una ry minu s (i.e., cha nge the sign of th e old value) a nd " A" t o indica te
a bsolute va lue. Wha t cha nges would need to be ma de to th e program ?
2. Suppose that words ra t her than s ingle cha racter symbols are to be used
for t he operat ors (e.g., th e user types " t imes" inst ead of " *" ). Wher e in
th e progra m w ould th e necessar y chan ges occur?
3. Suppose tha t t he ca lculat or is to be converted to use C+ + double values
ra th er tha n integers. Where would cha nges need to be ma de?
4. Most m odern systems support gra phica l displa ys a nd mouse (or other
pointer) input. Rewrite the C a lculat or progra m t o ta ke adva nta ge ofthese features to produce an on-screen push-button calculator (this is a
large programming project).
2 Not a ll computers will g enerat e incorrect r esults for 15,017 *4. However, all computers will
generat e an overflow for some int va lues.
-
8/10/2019 Large number.pdf
10/1024
5. Show how a new comma nd, "C" , which acts l ike the "Clear " comma nd on
a calculat or could be implement ed. The clea r comm a nd set s t he current
va lue to zero.
6. (AB only) H ow could th e ca lcula tor be modified to a llow t he use of
par entheses t o cont rol the order of operat ions?
Specification of BigInt
Well implement a new class BigInttha t performs a r i thmetic with values
that exceed those of the type int. Before proceeding, well develop a detailed
specification for the class BigInt. Sin ce th e specifica tion describes the new
cla ss a bstra ctly, wit h no reference to how it w ill be implemented, it is
referred t o as a n a bstra ct da ta ty pe, or ADT. The specificat ion includes
th e kinds of va lues th a t can be represent ed by the class BigIntand the
operat ions t ha t ca n be performed on the va lues.
Size l i mi ts:We wa nt no limit on t he size of BigIntvalues other tha n
th ose limits caused by t he finite memory of comput ers. In other w ords, w e
do not wa nt t o predeterm ine a limit on th e number of digits in a BigInt
va lue. This requirement w ill help determine how w e store the digits in a
BigIntobject .
Operations:Well ca t egorize BigIntopera t ions a s show n below. These
a rent a l l the opera tions t ha t can be performed, but a re more tha n enoughto implement th e calcula tor program . The opera tions w ill support other
progra ms tha t use BigIntva lues, too.
Fundamental Comparison
Constructors operator
I/O opera tor = =
operator >
Print Conversion
ToDouble
Arithmetic ToString
operator += ToInt
operator =
operator *=
-
8/10/2019 Large number.pdf
11/1025
Fu ll specificat ions for each of these funct ions w ill be provided lat er.
Most of th e functions d o exactly a s t he na me implies (i .e., operator+ = a d ds
BigIntva lues). Well provide a brief comm ent a ry here for th ose funct ions
a nd operat ors t ha t a re different from int functions.
We will implement severa l constructors. For exa mple, we w ill wa nt adefault const ructor so th a t w e ca n define vectors of BigIntva lues. Well wa nt
to construct a BigIntfrom a n int va lue. It w ill a lso be useful to const ruct a
BigIntf rom a str ing value since a st r ing ca n conta in as ma ny chara cters as
needed to represent a ny BigIntva lue. In some sense the int a nd str ing
const ructors allow us t o convert int a nd st ring va lues to corresponding
BigIntva lues. The " To" functions: ToDouble(), ToString(), and ToInt()permit
conversion in t he other d irection, e.g., ToDouble()converts a BigIntto the
corresponding double value.
Init ially w e will implement neither a destructor, nor a copy
const ructor, nor an a ssignment operat or for t he cla ss BigInt. These
functions a re necessar y only in cert a in situa tions so w e ma y need to revisit
th is decision la ter w hen w e decide how to implement BigIntva lues.
We show three a r i thmetic assignment operat ors: + = , = , a n d *= . As
w e will see, once these operat ors a re implement ed, the implementa tion of
th e corresponding a rith metic operat ors: + , , *is stra ightforw a rd.
-
8/10/2019 Large number.pdf
12/1026
Study Questions
1. Wha t a re the larges t and sma l lest in teger values in the programming
environment you use?
2. E a ch BigIntobject w ill need to store the digits t ha t r epresent t he BigInt
va lue. The decision t o allow a rbitra rily lar ge BigIntva lues a f fects the
choices for st oring digits. Na me one method for st oring digits th a t w ill
permit a n a rbitra ry nu mber of digits to be stored. Wha t effect w ould
a limit on th e number of digits in a BigIntha ve in t he design of the
BigIntcla ss?
3. B a sed on your know ledge of pencil-a nd-paper meth ods for doing
a ri thmetic, wh a t do you t hink wil l be the most dif ficult a r i thmetic
operat ion (+ , *, ) to implement for the BigIntclas s? Why ?
4. Experiment wi th the ca lcula tor. I f you enter abcd1234when a number
is expected, wha t h a ppens? If you enter 1234abcdis th e beha vior
different? Wha t h a ppens if you ent er a n opera tor th a ts not one of th e
three tha t a re implemented?
5. List a s ma ny operat ions a s you can tha t a re per formed on integers , but
th a t a re not included in the list of BigIntfunctions a nd opera tors a bove.
6. (AB only) Wha t implementa tion decisions w ould require providing a
destructor, a copy const ructor, a nd a n a ssignment operat or?
7. Consider the headers for operatorand operator+given below.
BigInt operator - (const BigInt & big, int small);
// postcondition: returns big - small
BigInt operator + (const BigInt & big, int small);
// postcondition: returns big + small
Write the body of operatorassuming tha t operator+ha s been writ ten.
-
8/10/2019 Large number.pdf
13/1027
Solution Narrative
Well begin by considering a nd r esolving some of th e missing specifica tions
of t he problem. Well move next t o the design of the d a ta str ucture
for storing a BigInt. D ifferent design possibilities a re explored a nd a
represent a tion of the fina l design evolves a s par t of this explora tion. Error
ha ndling wil l be discussed at this sta ge.
After d iscussing t he design, w ell move to th e BigInt implementation.
Several BigIntopera tions a re designed, coded, a nd t ested. The test s reveal
some wea knesses in the origina l design, an d these a re repa ired. Dur ing
th is process t he calculat or progra m is modified to ma ke use of BigInt
values. Opportunities for the use of BigIntva lues in different cont exts
a re exa mined, too.
Design Goals
The class BigIntwill be implement ed as a hea der file declar ing th e class
a nd a corresponding im plement a tion file consisting of th e member
functions of the cla ss a nd other non-member functions used t o man ipulat e
BigIntobjects. Through out our discussion, w e w ill refer to t he decla ra t ions,
operat ors a nd functions as t he class a nd t he ca lcula tor (or other) progra m
using t he class a s t he client progra m. A w ell-designed class can be used
with a ny client program w ithout cha nging the class .
The cla ss sh ould:
be convenient and intui t ive for programmers to use;
be useful in a w ide var iety of appl ica t ions ;
mimic oper a t ions on C+ + integer s so tha t a progr am wr it ten
a nd debugged using int va lues can be quickly an d relia bly
convert ed to use BigIntvalues; a nd
ut i lize informat ion hiding; it should be poss ible to use BigInt
varia bles w ithout knowledge of the un derlying da ta structures
or a lgorithm s used.
-
8/10/2019 Large number.pdf
14/1028
Overall Structure
The ca lcula tor progra m w ill be orga nized as sh ow n in th e diagra m below:
Calculator (client) program calc.cpp
BigInt, operator+, ToInt, operator
-
8/10/2019 Large number.pdf
15/1029
Error Handling
As the sa mple run of th e ca lcula tor progra m ea rlier showed, ar ithm etic can
result in errors beca use of th e limited r a nge of values of th e type integer.
Er rors can result from ba d I /O, too. For exam ple, if you enter " a pple" wh en
a progra m expects a numeric value a n error usua lly occurs. These sam e
kinds of errors will occur w hen BigIntopera tions a re used. As pa rt of the
design of the clas s, well need to decide how t o ha ndle such errors. For
example, I/O errors could be ha ndled by r eading a ll input using str ings so
tha t bad inputs (e.g. , a lett er instead of a digit) are tra pped internally.
Fun ctions for I /O, a rithm etic, a nd oth er BigIntoperat ions w ill need to
indicate that an error has occurred or handle the error. Well consider
severa l options for ha ndlin g errors. It s possible, of course, t o avoid error
ha ndling ent irely. Client progra ms w ould th en be responsible for not ca llinga n y BigIntfunctions a nd opera tors th a t could cause errors. However,
ma king error-checking t he responsibility of the BigIntcla ss ma kes
developing client progra ms simpler. Well consider four m eth ods for
handling errors.
1. Errors ca n be ignored, opera tions a re performed as w ell as
possible. For exa mple, illega l va lues such a s 0139a bcd3 can
be convert ed t o zero.
2. Errors can be t ra pped, an er ror message pr inted , and theclient progra m ha lted.
3. An exception could be thrown w hen errors occur. Client
progra ms a re responsible for cat ching exceptions a nd t a king
appropriate action.
4. A BigIntcould include a special " error" va lue in a ddition to an
a rit hm etic va lue. The client pr ogra m is responsible for checking
a BigInterror sta tus a nd ta king a ppropria te a ction.
-
8/10/2019 Large number.pdf
16/10210
Ign oring errors is und esirable since it w ill lead to incorrect output
w ith n o indica tion tha t a n error ha s occurred. For exa mple, if the cla ss is
used in a ba nking program a nd a division by zero error results in improper
bookkeeping, cust omers w ont be ha ppy th a t errors h a ve been ignored t o
ma ke w riting t he class simpler.Sometimes ha lting a progra m is t he only course of a ction. For
example, out-of-bounds indexing of apstringand apvectorva ria bles stops a
client progra m a fter printing a n error messa ge. On th e oth er ha nd, if your
progra m is ha lted you might lose dat a .
U sing exceptions is probably t he best a pproa ch, but exceptions a re
not support ed at t his time by all C+ + compilers. Furt hermore, properly
designed exceptions rely on inheritance, a topic not currently covered in the
AP Comput er Science course description.
Ma king client progra ms check for errors offers flexibility since
progra mmers ca n decide w hen t o check for errors. However, a ssocia ting a n
error va lue with each BigIntma y complica te t he coding of th e arit hmet ic
operations since well need to handle error values appropriately.
Well choose th e second met hod for ha ndlin g errors: t he errors w ill be
tr a pped in the implement a tion of the BigIntmember functions, an error
message printed, a nd t he progra m ha lted. This ha s dra wba cks, but mirrors
the a pproa ch ta ken by the apmatrixand apvectorclasses.
Study Questions
1. Consider the error han dling provided by your C+ + system. Wha t does
th e system do if a file is not present in a call to open? Wha t ha ppens on
int eger overflow or divide by zero? Det ermin e wh ich meth od(s) a re used
a nd discuss the rela tive desirability of oth er options.
2. List severa l er rors that might be generated by BigIntoperat ions a nd
develop a declar a tion for a n enum era ted t ype (enum) to hold th e errors.
3. Some systems al low error checking t o be turned off entirely for great er
speed. Un der wha t circumst a nces is this a pproa ch preferred?
-
8/10/2019 Large number.pdf
17/10211
4. Consider a nother method for ha ndling errors :
U se an intera ctive error-ha ndling a pproa ch. An error messag e is
displa yed to th e user w ho then h a s t he option of (a ) correcting t he
va lue tha t caused t he error, (b) ha lting t he progra m, or (c) ignoring
t he error.
Describe the strengt hs a nd w eaknesses of this approach.
5. Consider a nother method for ha ndling errors :
Er ror results a re stored in a single globa l var iable. This is set
initia lly to indicat e a no error condition. Whenever a n error is
detected, th e globa l varia ble is set t o a n a ppropriat e va lue, a nd
th e client progra m is responsible for exam ining t he va lue of th e
global variable.
Describe the strengt hs a nd w eaknesses of this approach.
Formal Specifications for BigIntFunctions
We ca nnot w rite code unt il we ha ve specified exactly w ha t each function
is t o accomplish. These specifica t ions w ill include det a iled pre- a nd post -
condit ions for ea ch BigIntfunction. Function prototy pes wit h pre- a nd post-
condit ions ar e shown below for th e principle BigIntfunctions. In severa l of
the prototypes the para meters are na med lhsand rhsfor left-ha nd side a ndrigh t-ha nd side, respectively. For exam ple, in t he expression if (big == 3) th e
argument bigis pa ssed to the para meter lhsand the argument 3is passed
to the para meter rhs.3
3 In ma ny of the BigIntprototypes, para meters a re declar ed as const reference para meters, e.g. ,
in the BigIntconstr uctor from a n apstring, th e prototype is BigInt(const apstring & s). Reference
para meters a re used to save tim e and memory since no local copy is made for a r eference
parameter whereas a local copy is made when parameters are passed by value. The constmodifier
ma kes it impossible to modify t he pa ra meter, so the efficiency of pass-by-reference is obtained
wit hout sa crificing the sa fety of pass-by-value. U nless there is a reason to ha ve a local copy, class
ty pes (e.g., apstringand BigInt) para meters should be constreference ra ther tha n va lue.
-
8/10/2019 Large number.pdf
18/10212
Constructors
BigInt::BigInt()
// postcondition: bigint initialized to 0
BigInt::BigInt(int num)
// postcondition: bigint initialized to num
BigInt::BigInt(const apstring & s)
// precondition: s consists of digits only, optionally preceded
// by + or -
// postcondition: bigint initialized to integer represented
// by s if s is not a well-formed BigInt (e.g.,
// contains non-digit characters) then an error
// message is printed and abort called
I / O
ostream & BigInt::Print(ostream & os) const
// postcondition: BigInt inserted onto stream os
ostream & operator (istream & in, BigInt & big)
// postcondition: big extracted from in, must be whitespace
// delimited
Ar i thmet ic
const BigInt & BigInt::operator -=(const BigInt & rhs)
// postcondition: returns value of bigint - rhs after
// subtraction
const BigInt & BigInt::operator +=(const BigInt & rhs)
// postcondition: returns value of bigint + rhs after
// addition
const BigInt & BigInt::operator *=(const BigInt & rhs)
// postcondition: returns value of bigint * rhs after
// multiplication
-
8/10/2019 Large number.pdf
19/10213
Comparison
bool operator == (const BigInt & lhs, const BigInt & rhs)
// postcondition: returns true if lhs == rhs, else returns false
bool operator != (const BigInt & lhs, const BigInt & rhs)
// postcondition: returns true if lhs != rhs, else returns false
bool operator > (const BigInt & lhs, const BigInt & rhs)
// postcondition: returns true if lhs > rhs, else returns false
bool operator < (const BigInt & lhs, const BigInt & rhs)
// postcondition: returns true if lhs < rhs, else returns false
Assignment and Conver sion
apstring BigInt::ToString() const
// postcondition: returns apstring equivalent of BigInt
int BigInt::ToInt() const
// precondition: INT_MIN
-
8/10/2019 Large number.pdf
20/10214
B igInt operat ions a ccess individual digits. F or exam ple, th ree possible
meth ods for st oring th e digits in t he number 1,234,567 in a n a rra y a re
diagrammed below.
1 2 3 4 5 6 7 . . .
7 6 5 4 3 2 1 . . .
. . . 1 2 3 4 5 6 7
Each BigIntha s a r ightm ost or least signif i cant d igi t(LS D) and a leftm ost
or most signi f icant di git(MS D). In 1,234,567 the LS D is 7 an d t he MS D
is 1. P rinting req uires accessing digits from the MSD to the LS D. Numbers
a re also entered by typing the MSD first , so the LSD of an entered BigIntis
stored last . Arithm etic operat ions, however, usua lly require a ccessing th e
LS D first. For exa mple, th e typica l method for a dding integers, using the
a dd-a nd-carry a pproa ch dia gra mm ed below, a ccesses the LS D first a nd
stores th e MSD of the result last .
11 61 3
+ 5 8
2 2 1
The choice of how digits a re stored in a n a rra y ha s a big effect on
how difficult it w ill be to implement th e BigIntopera t ions. A poor d esign
decision can be ha rd t o undo, so careful thought is needed a t t his point. Noma tt er how we store the digits w e wil l try to separa te the implementa tions
of BigIntfunctions from t he precise wa y in w hich digits a re stored. We will
str ive, for example, to design a class so tha t sw itching th e order in wh ich
digits a re stored in a n a rra y a f fects only a few BigIntfunctions, an d none of
th e functions outlined a bove a s t he core BigInt functions.
We do th is by sepa ra ting t he physica l layout of the digits from t he
logica l wa y t he digits a re used. Well number each digit in a BigInts tar t ing
w ith zero as t he number of th e lea st significa nt digit. For the four digit
num ber 5,679 th e 9 is the 0th digit . We ca n a lso sa y t ha t t he 9 has index 0.
The 7 ha s index 1, th e 6 index 2, and th e 5 has index 3. In general, t he
-
8/10/2019 Large number.pdf
21/10215
most significant digit of a BigIntwit h n digits ha s index (n1). To a chieve
th e separ a tion of logica l an d physica l layout w ell use th ree priva te member
functions t o access digits. This mea ns t ha t BigIntfunctions tha t a ccess
digits w ill not a ccess an a rra y directly, but w ill a ccess digits only th rough
th e privat e digit-ma nipulat ing member functions. With t his a pproa ch, onlyth e privat e functions w ill need to be reimplemented if th e physica l lay out
of digits is chan ged. For exam ple, if we chan ge the implementa tion to use
built-in arra ys rat her tha n the apvectorcla ss only the privat e functions
w ill need to be rewrit ten. S imilarly (AB only) if we use a linked list t he
chan ges ar e isolat ed in the privat e functions. Specificat ions for th e priva te
functions follow.
int BigInt::NumDigits() const
// postcondition: returns # digits in BigInt
int BigInt::GetDigit(int k) const
// precondition: 0
-
8/10/2019 Large number.pdf
22/10216
The fin a l BigIntcla ss will use a cha r vector to store individual digits, a nd
digits w ill be stored a s shown in th e second of the dia gra ms a bove, i.e.,
w ith t he lea st significa nt d igit stored in th e first a rra y element (index 0).
Note t ha t t his ma kes the physica l index correspond t o the logica l index.
For exa mple, th e lea st significa nt digit ha s physica l index zero in th evector an d logical ind ex zero accordin g to th e scheme discussed a bove.
H ow ever, it s not ha rd t o cha nge th e order in w hich digits a re stored.
Since the cha nges a re isolat ed in the priva te member functions GetDigit,
ChangeDigit, and AddSigDigitmost of the BigIntcode w ont need t o be
chan ged if th e physical la yout of digits is cha nged. The releva nt par ts
of t he privat e section of the hea der file bigint.ha re reproduced here.
Additional priva te helper functions a re shown in Appendix B w here th e
complete header file is shown.
private:
// private state/instance variables
enum Sign {positive,negative};
Sign mySign; // is number positive or negative
apvector myDigits; // stores all digits in number
int myNumDigits; // stores # of digits in number
// helper functions
int GetDigit(int k) const; // return digit (or 0)
void AddSigDigit(int value); // add new most sig digit
void ChangeDigit(int k, int value); // change digit to value
-
8/10/2019 Large number.pdf
23/10217
A new str uctur e for th e pr ogr am
The use of three privat e member functions cha nges t he str ucture of the
BigIntclass. The new st ruct ure is show n below. A client progra m ca n only
access BigIntva ria bles using th e functions in th e public section of bigint.h.
The decision on how digit s a re physica lly stored in t he vect or myDigitsis
isolat ed in the privat e member functions.
Calculator (client) program calc.cpp
BigInt, operator+, ToInt, operator
-
8/10/2019 Large number.pdf
24/10218
Implementation of the Large Integer Package
Building the Scaffolding: Fundamental and I/O Functions
We now tur n t o the implement a tion of the t ype BigInt. Rat her tha n code
a ll of the subprogra ms a t once, we wil l implement t hem a few a t a t ime,th oroughly t est th em a s we go, and t hen move on t o oth ers. This w a y, wh en
a n error is discovered, the sma ll am ount of untested code is the m ost likely
source of the error.
We begin w ith fun ctions for const ructing, rea ding, a nd w riting BigInt
va lues. When t hese operat ions ha ve been implement ed, we w ill ha ve a
reliable wa y of enter ing a nd printing values so tha t w e ca n t est other
functions. Well also be attentive to potential problems in our initial design
of BigInt. Coding a t t his early sta ge often reveals am biguities a nd problems
in t he specifica t ion a nd d esign decisions. Well implement const ruct ors
first, then t he output functions Print()and operator .
The const ructors must initia lize a ll priva te da ta fields of a BigInt.
The postcondition of the default or pa ra meterless constructor sta tes th a t a
BigIntis init ia lized to zero. This lea ds t o the follow ing code.
BigInt::BigInt()
// postcondition: bigint initialized to 0
: mySign(positive),
myDigits(1,'0'),
myNumDigits(1)
{
// all fields initialized in initializer list
}
-
8/10/2019 Large number.pdf
25/10219
The apvectorfield myDigitsis initia lized t o cont a in one digit so tha t
the BigIntrepresent s zero. In itia lizer lists a re th e preferred method for
constructing priva te da ta a nd sett ing init ia l values, al though i t is possible
to initia lize all fields in t he body of the const ructor a s shown below.
BigInt::BigInt()
// postcondition: bigint initialized to 0
{
mySign = positive;
myDigits.resize(1);
myDigits[0] = '0';
myNumDigits = 1;
}
Init ia l izer lis ts a re preferred when privat e dat a must be constructed a s
w ell a s being given initial va lues. In some ca ses, th ere is no a lterna tive to
initia lizing cla ss dat a in a n initia lizer list. For exa mple, if th e apvector
cla ss ha d no defa ult (par a meterless) const ructor, the privat e dat a field
myDigitswould need to be const ructed w ith a n initia l size in a n initia lizer
list. In t he exa mple above w hen a n initia lizer list is not used, myDigitsis
first const ructed t o cont a in zero element s, th en resized t o cont a in one
element . In some situa tions this is very inefficient since da ta will be
constructed, then given a n init ial va lue in a sepa ra te sta tement, unless
initia lizer lists a re used. In th e exa mple above, more code is required w heninitia lizer lists ar e not used.
There a re tw o oth er const ructors th a t serve as conversion functions
from integers an d strings t o BigInts. These ar e not sh ow n here but a re
shown in Appendix C. B oth const ructors peel digits off one a t a time a nd
store them in a BigIntusing th e priva te member function AddSigDigit().
The AddSigDigit()funct ion is r esponsible for resizing t he vector myDigits
w hen necessa ry.
-
8/10/2019 Large number.pdf
26/10220
Reading BigIntvalues w ill be fa cilita ted by th e const ructor tha t
converts a str ing6to a BigInt. Since str ings ca n be rea d from a ny input
stream , we ca n read a str ing a nd convert the str ing to a BigIntva lue.
This a pproach is show n below for operator >>. The input st rea m mu st
be retu rned from the function t o fa cilita te cha ining input opera tionsas follows.
cin >> x >> y >> z;
U sing str ing input for BigIntinput mea ns th a t it w ill not be possible to read
a BigIntva lue unless it is follow ed by w hitespa ce. This is a sma ll price to
pay for th e ea se with w hich weve implemented input for BigIntva lues.
istream & operator >> (istream & in, BigInt & big)
// postcondition: big extracted from in, must be whitespace
// delimited
{
apstring s;
in >> s;
big = BigInt(s);
return in;
}
Input comes from t he istream para meter inso tha t it w ill be possible
to rea d from a ny strea m ra ther th a n being l imited to rea ding from
the keyboard.
It s difficult to t est t he code for t he const ructors a nd for input
with out the function Printto displa y BigIntva lues. Nevertheless, we sh ould
th ink a bout test ing t he code by considering potent ial problems. For
example, we must deal w ith t he possibility of a leading '+ ' or '' sign . We
must a lso decide how to deal wit h non-digit chara cters. For example, w ha t
a ction should we ta ke if the user enters 123af45? Thinking a bout th ese
th ings ma y point out conceptua l errors in t he code. However, unt il we ha ve
a w a y of pr inting BigIntva lues we will not be a ble to test t he functionsth orough ly. The code in Appendix C shows t ha t m a lform ed BigIntvalues
w ill cause a progra m t o a bort execut ion.
6 Strings a re implemented using the class apstring.
-
8/10/2019 Large number.pdf
27/10221
We now proceed t o the out put funct ions Print()and operator
-
8/10/2019 Large number.pdf
28/10222
Testing the Class
To test th e functions weve writt en well write a progra m t ha t includes the
hea der file bigint.ha nd w hich links in th e implementa tion file bigint.cpp.
On ma ny systems, including Sym a ntec C+ + , Metrowerks Codewa rr ior,
Visual C+ + , and B or land C+ + , tes t ing a mul t if ile program requires us ing
a project 7. On some syst ems it is possible to include implementa tions
(i.e., .cpp files) in a library th a t is linked au toma tically w ith client test
progra ms. Well a ssum e, however, tha t a project is used. To test t he BigInt
implement a tion we include bigint.cppand apstring.cppin t he project. On
some syst ems apvector.cppmust a lso be in th e project. P rogram ming
environment s a re sma rt enough not t o recompile th e string a nd vector
implement a tions w hen only th e client test progra m cha nges. Therefore,
w e dont expect our test progra m t o ta ke long t o compile, a lthough itis comm on for ma ny sy st em files (e.g., iostream.h) to require length y
compilation.
We must a lso provide documenta tion in t he hea der file bigint.hso
th a t a progra mm er ca n use our cla ss effectively with out a ccess to th e
implement a tion. The document a tion in bigint.hshould cont a in enough
informa tion for t he cla ss t o be used, and n o more. We dont w a nt t o ment ion
implementa tion deta i ls tha t m ight change. Unfortuna tely, the privat e
section of classes is shown in C+ + hea der files so users can see some
information about the implementation, although client programs cannot
a ccess priva te da ta or call privat e functions. Although t here ar e methods
for concea ling th e privat e section from client progra ms, t hese require using
either pointers or inh erita nce. Therefore, we w ill be cont ent w ith revealing
some deta ils of th e BigIntimplement a tion in th e priva te section of the cla ss
declar a tion. Appendix B shows t he hea der file bigint.h.
The progra m testio.cpps imply reads a nd prints BigIntvalues
entered by the user. Since input a nd output use th e string const ructor and
conversion fu nction ToString(), these functions ar e tested using testio.cpp.The t est progra m is in Appendix E.
7 Informa tion on how to use projects is accessible via t he case study web pa ge.
-
8/10/2019 Large number.pdf
29/10223
We must carefully choose test da ta for even a sma ll program like
testio.cpp. In t esting any progra m, we w ish to test a few typica l values, al l
edge case or bounda ry va lues, a nd a va riety of error va lues to ensure tha t
th e code is robust. F or test ing th is progra m, w e tested va rious lengths of
integers, including length s of one digit, a few digits, a nd h undreds of digits.We also tested num bers wit h lead ing '' a nd '+ ' cha ra cters , an d embedded
'' a nd '+ ' char a cters. Fina lly, we entered sequences cont a ining lett ers at
th e beginning, end, a nd m iddle to see how our code ha ndles error va lues.
One series of tests genera ted incorrect results. If a num ber wa s
entered w ith leading zeroes (e.g., 00345) the program stored a nd printed
th e lea ding zeroes. En tering t he sequence 0000 genera ted t he sequence
0000. We did not a nt icipa te t his ca se in specifying a nd d eveloping t he code.
We w ill dea l w ith th is problem in t he next section.
Study Questions
1. List a l l the va lues you would use to test the I/O functions a nd the str ing
conversion functions thoroughly. G ive an explana tion for ea ch da ta set
describing its importance. How could you modify testio.cppto test the
constructor that has an in t para meter?
2. The stream member funct ion width()can be used to specify a fieldwidt h
wh en genera ting output . Do you expect it to work correctly w ith BigInt
values? Modify testio.cppt o see if width()w orks a s intended.
3. A reference to an uninit ia l ized va r iable ca n genera te a n error in some
C+ + environments. The default BigIntconst ruct ors could be m odified t o
detect t ha t a var ia ble ha s not been given a value. Instead of init ia l iz ing
a BigIntva ria ble to zero, t he const ructor could leave t he BigIntin an
uninitia lized sta te. With t his knowledge, we ca n genera te a n error
sta tus i f an a tt empt is ma de to exa mine the value of such a var ia ble.
Describe in some deta il how th is might be implemented.
4. Wha t m odifica tions w ould need to be made for th ese functions to
represent a nd ma nipulat e numbers in ba se 3? In ba se 2? Show how a
const a nt could be used to var y th e base of th e number syst em in use.
-
8/10/2019 Large number.pdf
30/10224
Refining Our Implementation
The sam e int eger can be represented in ma ny different w a ys by a dding
lead ing zeroes. For exa mple, 012 a nd 00012 both represent t he num ber
tw elve. This poses a problem since w e w ould prefer t ha t va ria bles holding
th e sam e value ha ve the sa me represent a tion. Two a pproa ches to resolving
th is seem reasona ble:
1. Allow this a mbiguity, but let the va r ious functions resolve i t a s
necessar y. For exa mple, Print()can a void printing lead ing zeroes.
2. R epr es en t a l l BigIntva lues without lea ding zeroes. Ea ch function
th a t might produce lea ding zeroes (e.g., operator >>) w ill need to
trim t hem off.
We chose th e second met hod since it m ore closely resembles h ow w e th inkof integers (i.e., leading zeroes are not written or stored).
The input function (a ctua lly, th e const ructor tha t convert s a str ing
to a BigInt) w ill need t o trim leading zeroes before retur ning. S ince this
is likely to be a n opera tion needed by other fun ctions, but not by client
progra ms, w ell implement a privat e function t o trim leading zeroes.
B eca use were not sure wha t other conditions might a r ise tha t require
conversion t o a comm on form w ell ca ll th e function Normalizer a ther
th a n something seemingly more appropriat e like TrimZeroes. A va lue is
norma lized when i t is in a sta nda rd forma t. For exa mple, in a cla ss for
represent ing fra ctions (ra tiona l numbers) we might convert a ll fra ctions
to low est t erms, e.g., Fra ction a (6,9) w ould represent tw o-th irds w hen
normalized.
void BigInt::Normalize()
// postcondition: all leading zeroes removed
Fina lly, one specia l ca se remains. S uppose tha t a BigIntconsist s
entirely of zeroes, i .e., i t r epresents th e num ber zero. S hould the fina l
zero be trim med or sh ould it r ema in? Well st ore one digit '0' since it
more closely ma tches our int uitive idea of a represent a tion for zero, i .e.,
a single digit 0. We must a lso consider th e idea of a "n egat ive zero." If you
enter 00000, should th is be t rea t ed differently t ha n + 0000? S ince one of
th e design decisions w e ma de is to ha ve only one wa y of representing zero,
well use a positive zero only.
-
8/10/2019 Large number.pdf
31/10225
The h ea der for Normalize()does not a ppear in t he public section of
th e class d eclar a tion since client progra ms w ill not need to ca ll it . The
Normalizefunction is shown in Appendix C; it is called from t he BigInt
str ing const ructor to trim zeroes tha t ma y be pa rt of the string being
converted t o a BigInt. As w e develop other funct ions, Normalizew ill becalled whenever it is possible th a t a number cont a ins lea ding zeroes.
Study Questions
1. Suppose tha t w e decide not t o el imina te lea ding zeroes unti l necessa ry.
Which of the BigIntfunctions migh t generat e leading zeroes? Which
might need t o el iminat e them from para meters i f they w ere present?
2. Wha t ha ppens to the s ize of the priva te var iable myDigitsif the user
ent ers 100 zeroes? Is t his desira ble?
3. Wha t a r i thmetic opera tions ca n introduce leading zeroes?
4. D es cr ib e h ow a Normalizefunction for ra tional n umbers (fra ctions)
might convert to lowest terms (so tha t numerat or a nd denominat or ha ve
no comm on fa ctors).
Comparison Operations
After verifying th a t our code can reliably rea d a nd w rite BigIntva lues,
w e ma y proceed to develop th e ot her BigIntsubpr ogra ms. We choose to
implement th e compa rison opera tions first because t hey a re reasona bly
simple and may be useful in creating more complex functions (e.g.,
subt ra ction, mult iplica tion). Well check for equa lity firs t, t hen develop
code for BigInt inequalities.
As we noted earlier, checking for equality requires accessing
individual digit s of BigIntva lues. Since digits a re accessed using th e priva te
member function GetDigit(), the function tha t checks for equa lity w ill need
to be a ble to ca ll GetDigit(). Idea lly we w ould like to overloa d operator ==s otha t w e ca n compare BigIntva lues using code like if (a == b). How ever, we
ca nnot ma ke operator ==a member function.8We could ma ke operator ==a
8 If we implement operator ==a s a member funct ion i t will have one parameter s ince the s ta tement
if(a.operator == (3))is another way to write (a == 3) when == is a member function. It is not possible
to writeif(3.operator == (b)) ins tead ofif(3 == b) since 3 is an int a nd ha s no member functions.
Since we would like to write both if(3 == b) a nd if(b== 3) we make operator == a non-memb er (or
free) function. Then if(3== b) is simply a nicer wa y of wr iting if(operator == (3,b)) which w orks
because the 3 can be converted t o a BigIntsince there is a BigIntconstructor w ith a n int param eter.
-
8/10/2019 Large number.pdf
32/10226
friend function. Friend functions an d cla sses ca n a ccess privat e dat a . In
general, it s a good idea to a void using friend functions a nd classes since
gra nt ing a ccess to privat e informa tion doesnt conform to th e goa ls of
informa tion hiding. Inst ead of using friend functions, w ell write a public
helper member function BigInt::Equal()to ma ke it possible t o overloadoperator ==just a s th e member function BigInt::Print()ma de it possible to
overload operator 23, the code must
recognize that 34 < 23. In w riting t he code, we ta ke th e same genera l
a pproa ch as we used with BigInt::Equal():we deal with the signs a nd
lengths first, a nd t hen w ith t he sequence of digits. To implement operator
-
8/10/2019 Large number.pdf
33/10227
w ell implement a helper fun ction BigInt::LessThan(). Well see th a t both
operator can t hen be implement ed easily. In t he body
of LessThanw e first check to see if th e sign of BigInt rhsis different t ha n
th e sign of th e BigIntfor wh ich t he member fun ction is ca lled (self in t he
comm ents below ). If t he signs a re different, self is less t ha n rhsonly if itis negat ive a nd rhsis positive.
bool BigInt::LessThan(const BigInt & rhs) const
// postcondition: return true if self < rhs, else returns false
{
// if signs arent equal, self < rhs only if self is negative
if (IsNegative() != rhs.IsNegative())
{
return IsNegative();
}
Next we t a ke ca re of values w ith different num bers of digits. Since
both num bers ha ve the sa me sign, individua l digits dont n eed to be
examined t o determ ine wh ich is la rger. If both a re positive, then self is
sma ller if i t ha s fewer digits t ha n rhs(223 < 1234). S imila rly, if bot h a re
nega tive, then self is less tha n rhsif self ha s more digits (1234 < 123).
// if # digits arent the same must check # digits and sign
if (NumDigits() != rhs.NumDigits())
{
return (NumDigits() < rhs.NumDigits() && IsPositive()) ||
(NumDigits() > rhs.NumDigits() && IsNegative());
}
Fina lly, when both t he signs a nd th e lengths a re the same, we must
tr a verse th e digits from left t o right , searching for a digit th a t differs. The
signs of self an d rhsa nd t he va lue of the differing digits can be used to
determine if self is sma ller th a n rhs. The fina l code a ppear s in Appendix C.
Implementing operator
-
8/10/2019 Large number.pdf
34/10228
We now t urn to implement ing operator >; there a re two al terna tives.
We can w rit e code simila r t o the code developed for BigInt::LessThan(), but
reflecting t he difference betw een < a nd >. Alterna tively, w e can reuse the
code for operator lhs. This second a ltern a tive req uires mu ch less code.
bool operator > (const BigInt & lhs, const BigInt & rhs)
// postcondition: returns true if lhs > rhs, else returns false
{
return rhs < lhs;
}
We developed a sma ll progra m ca lled testcomp.cppto tes t = = , < and
>; it is in cluded in Appendix E. We a lso implement ed opera t ors =
since th ese ca n be implement ed easily in term s of th e operat ors alrea dy
implemented. Our test data includes:
1. pairs of values conta ining al l possible combinat ions of s igns:
123, 123
123, 123
123, 123
123, 123
2. combinat ions involving zero:
123, 00, 123
123, 0
0, 123
0, 0
3. comparing values with dif ferent num bers of digi ts .
-
8/10/2019 Large number.pdf
35/10229
Study Questions
1. Wr it e operator !=and operator
-
8/10/2019 Large number.pdf
36/10230
Ea ch step in comput ing the sum of tw o digits in a digit sequ ence ma y
genera te a carry for th e next st ep and ma y use a ca rry from t he previous
st ep. This lead s t o th e pseudocode below.
carry = 0;
for each position from right to left of the numbers dosum = sum of digits from numbers plus carry
place sum % 10 as new most significant digit of answer
carry = sum / 10
if carry != 0
place carry as new most significant digit of answer
We th en t ra nsla te ea ch port ion of th is pseudocode into C+ + . The loop
begins at th e rightmost digit of ea ch number a nd proceeds to the leftmost
digit of the la rger num ber. We will use th is idea t o implement operator +=.
In general, it is ea sier an d prefera ble to implement such operat ors firsta nd t o then implement corresponding operat ors like operator +in terms
of operator +=. For exam ple:
BigInt operator + (const BigInt & lhs, const BigInt & rhs)
// postcondition: returns a bigint whose value is lhs + rhs
{
BigInt result(lhs);
result += rhs;
return result;
}
The oth er ar ithm etic opera tors a re implemented a s easily using
th e corresponding a rith metic assignm ent opera tor. We now tu rn t o
implementing addition using operator +=. To access a ll digit s of both
operan ds sta rt ing from the least significant digit (th e 0-th digit) w ell
use the code below.
const BigInt & BigInt::operator +=(const BigInt & rhs)
// postcondition: returns value of bigint + rhs after addition
{
int sum;
int carry = 0;
-
8/10/2019 Large number.pdf
37/10231
int k;
int len = NumDigits(); // length of larger addend
if (len < rhs.NumDigits())
{
len = rhs.NumDigits();
}
for(k=0; k < len; k++)
// process digits to form sum
In a ccessing the digits of ea ch number, we must h a ndle the ca se
w here one of the num bers ha s fewer digits th a n t he oth er. For exam ple,
consider a ddin g 1,234,567 an d 999. At first , it migh t seem n ecessa ry t o
loop only th ree times a s ma ny t imes as t here are digits in th e smaller
num ber 999. Looping over digits seven t imes a s ma ny digits a s th ere are
in 1,234,567 migh t ca use problems beca use t here a re not seven dig its inboth num bers. Although it is possible to w rite t he code th is w a y, th e code
w ill be complica ted by special ca ses to differentia te w hich of th e a ddends is
sma ller: the first or second. Fortuna tely we ca n hide this situa tion in th e
privat e function GetDigit() so tha t i f we request a digit t ha t doesnt exist
(such a s t he fifth digit of 123) th e function GetDigit()w ill retur n zero. This
grea tly s implifies the code a nd lea ds t o th e loop below. We use a consta nt
BASEt ha t is assigned the va lue 10 to fa ci li ta te using other number bases.
It ma y be difficult t o implement a rithm etic in ba se 2 or ba se 16, but using
a consta nt BASE, init ia lly set t o 10, will help if we decide to implement
a r i thmetic in other ba ses.
for(k=0; k < len; k++)
{
sum = GetDigit(k) + rhs.GetDigit(k) + carry;
carry = sum / BASE;
sum = sum % BASE;
if (k < myNumDigits)
{ChangeDigit(k,sum);
}
else
{
AddSigDigit(sum);
}
}
-
8/10/2019 Large number.pdf
38/10232
It is also possible for th e ca rry t o be 1 a fter a dding a ll the digits a s
w hen a dding 357 + 662. We must check for t his a fter t he loop.
if (carry != 0)
{
AddSigDigit(carry);
}
At t his point in t he implementa tion, it m a kes sense to test operator +=
and operator +even t hough t hey only ha ndle numbers w ith t he sam e sign.
If th ere are a ny problems, we can fix them before cont inuing w ith a ddition
of num bers w hose signs a re different. We th en consider t he signs of th e
num bers being a dded. If th e signs of tw o num bers ar e both positive or
both nega tive, then t he usua l pencil-a nd-paper a ddition algorithm w ill
be sufficient to obta in the sum. On th e oth er ha nd, if the numbers ha vedifferent signs, then we need a subtra ction ra ther th a n a n a ddit ion. Since
w e know th a t w e will a lso be developing a subt ra ction function, we can use
it t o solve the problem of adding tw o numbers wh ose signs a re different.
This leads to th e initia l code segment below for a dding rhs9. (This code does
not w ork.)
if (IsPositive() != rhs.IsPositive()) // signs not the same,
// subtract
{
if (rhs.IsPositive()) // change sign of rhs
rhs.mySign = negative;
else
rhs.mySign = positive;
*this -= rhs; // x + y == x - (-y)
return *this;
}
// signs are the same
9 The expression *thisrefers to the object t o which th e BigIntrhsis a dded. Weve referred to t his a s
self in the code and in th e case stud y. For example, in evalua ting t he stat ement x +=y; yis passed
as the para meter rhsa n d xis referred to wit hin th e member function operator +=by *this. Students
in th e A course a re not responsible for understa nding *this.
-
8/10/2019 Large number.pdf
39/10233
Here we ma ke use of the a lgebra ic rela tionship tha t A + B = A (B )
to reduce the a ddition of terms w ith different signs t o a subtr a ction of
values with the sa me sign. Unfortuna tely the method above wil l not w ork
because the para meter rhsis passed as a const reference para meter a nd th e
const ness prevent s our code from modifying rhs. One al terna tive is to ma kea copy of rhsw hich can then be a l tered. Another a l ternat ive is to assume
th a t m ultiplica tion is implemented a nd w rite th e code below.
if (IsPositive() != rhs.IsPositive()) // signs not the same,
subtract
{
*this -= (-1 * rhs); // x + y == x - (-y)
return *this;
}
// signs are the same
An a lterna tive a pproa ch is to give operator +=the a bili ty to ha ndle
a ddition of a ny t w o numbers, regard less of signs. This w ould ma ke the code
for operator +=more complex, but w ould lead t o extr emely simple code for
operator =. We chose instea d to separ a te th e addit ion a nd subt ra ction
a lgorithm s into tw o different functions an d ha ve ea ch ca ll the oth er if
th e va lues to be add ed (or subtr a cted) ha ve different sign s. The code for
operator +=a ppea rs in Appendix C.
-
8/10/2019 Large number.pdf
40/10234
Study Questions
1. Write the code for operator=on the assumption that operator+=ca n
ha ndle any combina tion of signs.
2. Complete the code fra gment below t o use subtra ction w hen signs a re
different by creat ing a copy of rhswh ose sign ca n be cha nged.
if (IsPositive() != rhs.IsPositive()) // signs not the
// same, subtract
{
BigInt copy(rhs);
// change sign of copy, subtract, return result
3. (AB Only) In a lgori thm a na lysis , one usually uses the unit cost
a ssumption with r egar d to arith metic operat ions: each such operat ion is
O(1). Wha t is t he complexity (using big-Oh) for a dding BigIntva lues of N
digits? Ca lcula ting t he Nth Fibona cci number can be done in O(N) time
wh en int egers a re used. Wha t would t he big-Oh complexity be if BigInt
values a re used?
Testing Addition
To test operator+=, wel l f irst crea te a program tha t rea ds tw o values
a nd prints t heir sum. The progra m testadd.cppis given below a nd in
Appendix E. We could a lso modify t he calculat or progra m so t ha t it used
BigIntva lues to test operator+=, but a t t his point w ell use testadd.cpp.
#include
#include bigint.h
int main()
{
BigInt a,b;
while (true)
{
cout > a >> b;
cout
-
8/10/2019 Large number.pdf
41/10235
This program test s operator+directly a nd operator+= indirectly
since th is lat ter opera tor is ca lled from the first a s w eve seen. In order to
run t he progra m, w e must implement operator= since operator+=calls it .
Ra th er tha n implement it fully, how ever, we could crea te a stub function
th a t does noth ing but print a messa ge. This w ould let us concentra te onoperator+=a nd worry about operator=a f ter we have found a ny bugs
tha t might be in operator+=. Addit ion of a ll BigIntva lues w ith different
signs ca nnot be tested unt il operator=is fully implemented.
Aga in, w e must choose test da ta carefully. Some cat egories of test
da ta a re given below.
1. Values for a a nd b that require car ry ing.
2. Va lues of 0 for either or both of a a nd b.
3. Va lues tha t require growing the vector tha t s tores digi ts .
The Subtraction Algorithm
We now tur n t o replacing th e stub implementa tion ofoperator=w i th
w orking code. Well use the sa me a pproach w e used in operator+=to handle
different signs, th is time relying on th e a lgebraic rela tionship below.
x - y = x + (-y)
If th e signs of the num bers x a nd y differ, we can r ewrit e the problem using
a ddition. For exam ple, to perform t he subtra ction (3) (4), w e perform
the a ddit ion (3) + (4). You ma y notice tha t operator+=calls operator=
to han dle the ca se of different signs, and tha t operator=calls operator+=
to ha ndle different signs. S ince w e ar e implementing a cla ss, prototypes for
both opera tors a ppea r in t he file bigint.h.
The orga niza tion of th e code described a bove a llow s us t o proceed
with the subtra ction a lgori thm on the a ssumption th a t t he signs of the
par a meters a re the sam e. In t he pencil-a nd-paper a lgorith m, we norma lly
w rite th e longer num ber on t op. In other w ords, t o ca lcula te 45 126,most people rewr ite t his a s 126 45, perform th e subtr a ction (obta ining
-
8/10/2019 Large number.pdf
42/10236
81), a nd t hen cha nge t he sign of the result. We ca n simplify our a lgorithm
by performing t he sa me steps10. Ca re must be ta ken to ha ndle negat ives
properly (e.g., (45) (126) ). The follow ing code t a kes ca re of t hese ca ses:
// signs are the same, check which number is larger
// and switch to get larger number "on top" if necessary
// since sign can change when subtracting
// examples: 7 - 3 no sign change, 3 - 7 sign changes
// -7 - (-3) no sign change, -3 -(-7) sign changes
if (IsPositive() && (*this) < rhs ||
IsNegative() && (*this) > rhs)
{
*this = rhs - *this;
if (IsPositive()) mySign = negative;
else mySign = positive; // toggle sign
return *this;
}
// same sign and larger number on top
We ca n now pr oceed to the a ctua l algorit hm u sing t he pseudocode below.
for each digit from rightmost digit to leftmost digit of self
if my digit is greater than the digit from rhs
then subtract the digits and change my value
else regroup from the next place, subtract rhss digit,
and change my value
In th e pencil-a nd-paper a lgorith m for su btra ction, r egrouping or
borrowing is immediat ely propa ga ted a s far left a s necessar y. For example,
if 5 is subt ra cted from 1003, the subtr a ction of the un its digit results in a
regrouping operat ion car ried through t o th e thousan ds place:
0 9 9 13
1 0 0 3
- 5
9 9 8
10 The statement *this = rhs *thisma kes an ind irect recursive call of operator =. For example,
consider the statement big = 7where BigInt bha s the va lue 3. This can a lso be writ ten a s
big.operator =(7). In t his case bigis *thisin t he body of operator =. Because(*this) < rhssince
3 < 7, the s ta tement *this = rhs *thiswill be executed . This resu lts in execution of result = 3
wh ere result ha s the va lue 7 (see the code in t he Appendix C for operator ). Infinite recursion
isnt possible beca use if a < bthen it is not the case that b < a.
-
8/10/2019 Large number.pdf
43/10237
A simpler a lgorith m results if we ha ndle regrouping much like
carry ing in a ddition. If regrouping is required in subtra ction of some digit,
th e process is passed on t o th e next digit. When t ha t digit is subt ra cted,
a furth er regrouping ma y be generat ed, an d so on. We use this meth od in
our code.To ensure th a t t here ar e no leading zeroes, we must a lso call
Normalize().
The code for operator+=and operator=functions is given in
Appendix C. S ince w e ha ve alrea dy modified the calculat or program for
both a ddit ion a nd subtra ction of BigIntva lues, wel l use tha t a s a test
progra m ra ther th a n designing a dif ferent testing progra m.
Study Questions
1. Describe test da ta for the ca lculat or program for testing addit ion
a nd subtra ction. G ive a n explana tion for each da ta set describing
its importa nce.
2. Write functions (for prefix operat ors) operator++and operator
similar t o th e corresponding int eger functions. Ca ll the ad dition an d
subtra ction functions a s needed.
3. Wri te funct ions operator++and operator directly (i .e., wit hout using
your ad dition an d subt ra ction functions). Wha t is ga ined or lost interm s of time efficiency?
Multiplication
The pencil-and-paper algorithm for multiplication is diagrammed below.
2 6 3 4
4 7 2
5 2 6 8
1 8 4 3 8
1 0 5 3 6
1 2 4 3 2 4 8
-
8/10/2019 Large number.pdf
44/10238
This met hod involves repeat edly multiplying a num ber by one digit of th e
oth er num ber. Depending upon th e place of t he digit, t he resulting product
is mult iplied by a pow er of 10 an d t hen a dded t o the result. I n pseudo-code:
for each digit from rightmost to leftmost digit of the bottom
number do
multiply that digit by the top number
multiply this product by 10p-1(where p is 1, 2, 3, ...)
add this into the accumulated result
We can use operator +=for the a ddition. To facilita te t he
mult iplica tion by 10 a nd t he multiplica tion of tha t digit by t he top
num ber well implement a sepa ra te operat or for mult iplying a BigIntby
a single digit. Well use this function in implement ing t he more general
mult iplica tion by a BigIntva lue. Well a lso modify t he pseud ocode a bove
to a void t he calculat ion of 10p1tha t w ould require a loop. Ra ther tha n
calcula te increasingly lar ger powers of 10, well simply multiply t he t op
num ber by 10 each t ime thr ough t he loop over th e digits of the bottom
num ber. Thus to m ult iply 12345 by 678 (w here t he t op num ber is 12345)
w ell actua lly ca lcula te a s follow s:
12345 x8 + 123450 x7 + 1234500 x6 = 8369910
This met hod requir es only one mult iplica tion by 10 ea ch time
th rough t he for loop w hose pseudocode is given. B efore completin goperator *=w ell turn t o th e operat or t o mult iply a BigIntby a single digit.
Multiplication by an int
To multiply by a single digit w ell use a n overloa ded version of operator *=.
Note tha t t he para meter is an in t , no t a BigInt.
const BigInt & BigInt::operator *=(int num)
// postcondition: returns num *value of BigInt after
// multiplication
-
8/10/2019 Large number.pdf
45/10239
We must be ca reful with signs since mult iplica tion ca n cha nge th e
sign of a number a s w hen a posit ive number is multiplied by a negat ive
num ber. The implement a tion requires tr a versing digits from right to left
w hile keeping t ra ck of a ny carry. Our first sketch of the a lgorithm looks
like this:
len = NumDigits();
for(k=0; k < len; k++) // once for each digit
{
product = num *GetDigit(k) + carry;
carry = product/BASE;
ChangeDigit(k,product % BASE);
}
while (carry != 0) // carry all digits
{
AddSigDigit(carry % BASE);
carry /= BASE;
}
This code is ada pted from t he a ddition algorithm; it d iffers in tw o w a ys.
1. P roduct i s ca lcula ted dif ferent ly tha n sum is ca lcula ted .
2. I f carry is a multi-digit number, processing carry a f ter the for loop
requires a nother loop.
We a re designing th is function t o han dle multiplicat ion of a BigIntby a
single digit, but a s part of a defensive progra mm ing stra tegy w e should
ta ke steps to ensure th a t t he function can h a ndle multiplicat ion of BigIntvalues by a ny intva lue. For exa mple, if numis too large, the sta tement
below could result in a value larger t ha n INT_MAX.
product = num *GetDigit(k) + carry;
I f numis nea r INT_MAXa nd t he current digi t is near 9, then the result wil l
be larger tha n INT_MAX. On some syst ems th is will generat e an error, on
others it ma y produce erroneous results. We could wr ite a precondit ion
specifying a limit on th e values of para meter numtha t t he function ha ndles
correctly. For exa mple, th e follow ing precondit ion limit s t he va lues of numto single digits a nd t he number 10 (w hen BASEis 10).
// precondition: 0
-
8/10/2019 Large number.pdf
46/10240
Client progra ms w ould t hen be responsible for ca lling t he function
only w ith va lues tha t sa tisfy t he precondition. Alterna tively, we could
ma ke the single digit version of operator *=a pr ivat e function so tha t i t
is not a ccessible to client progra ms but can be ca lled only from member
functions. Inst ead, w ell convert int eger va lues th a t a re not single digitst o BigIntva lues.
Fina lly, we must deal w ith t he signs of the numbers being
mult iplied. This is a much simpler problem for mult iplica tion t ha n it is for
a ddition. If the signs of tw o numbers being multiplied a re different, th e
result is nega tive. Otherw ise, it is positive.
Code for operator *=for both BigInta nd digit s is given in Appendix C.
To test th a t t he functions w ork, the calculat or program can be used. Ca re
must be ta ken in t esting al l bounda ry or edge ca ses with operat or *= for
BigIntva lues. For exa mple, w e must verify th a t different combina tions of
signs lead t o correct results a nd a lso th a t m ultiplicat ion in w hich one or
both of the nu mbers is 0 is ha ndled correctly.
Study Questions
1. The multiplica tion a lgori thm multiplies th e top number by 10 ea ch t ime
th rough th e loop over th e digits of the bott om n umber. An a lterna tive
meth od is to work from the leftm ost digit d ow n t o th e rightm ost digit
of th e bot tom n umb er. For exam ple, to mult iply 456 by 123, w e dothe following:
Mult iply 456 by the leftmost d igit in 123: 1 *456 = 456
Mult iply t he result by 10: 456 *10 = 4560
Mult iply 456 by t he next digit of 123
a nd a dd t o previous result : 4560 + 2 *456 = 5472
Mult iply t he result by 10: 5472 *10 = 54720
Mult iply 456 by t he next digit of 123
a nd a dd t o previous result : 54720 + 3 *456 = 56088
Modify operator *= (const BigInt & big)to use this a pproa ch.
2. (AB Only) Find a big-Oh expression for th e runtime of operator *= (const
BigInt & big)w hen a pplied to tw o N-digit nu mbers. Find a n expression
for m ult iplying one N-digit BigIntby a digit using operator *= (int num).
-
8/10/2019 Large number.pdf
47/10241
3. It s possible to write functions to handle adding BigInta nd int va lues
specially just as we developed two operators for multiplication: one for
BigIntva lues an d one for int va lues. We ca n implement a ddition an d
subtra ction operat ors in tw o wa ys:
(a ) by converting the integer to a BigInta nd cal l ing t he appropria te
BigIntopera t or; or
(b) by w riting special code to implement t he operat ion via low -level
reference to the int erna ls of BigInt.
Discuss the a dvan ta ges and disadva nta ges of (a ) vs (b).
4. Develop a precondition for BigInt::operator *= (int num)th a t describes the
ra nge of values for numth a t d o not r esult in overflow.
Aliasing: A New Problem Arises
The test progra ms revea led no problems wit h t he implement a tion of a ny
of t he BigIntfunctions, nor did the calcula tor progra m show a ny problems.
B eca use w e use overloa ded a rithm etic an d I /O opera tors for BigIntva lues,
modifying the ca lculat or progra m w a s stra ightforwa rd a nd required
chan ging only tw o definitions for t he var iables currentand accumulator.
H ow ever, w e th en implement ed th e function below for ra ising BigIntvalues
to a pow er a nd found some surprising results. This function is from a clientprogra m, it s not par t of the class BigInt.
BigInt power(const BigInt & a, int n)
// precondition: 0
-
8/10/2019 Large number.pdf
48/10242
for a BigIntra ised to an int pow er (th e correct result is shown in
parentheses).
72 = 49 (49)
122= 164 (144)
172= 1309 (289)
554 = 16803875 (9150625)
On some comput ers different results m a y a ppea r, but t he results
w ont be correct. It s difficult to tr a ck dow n t his bug, but since we know
tha t the f irst t est progra ms generat ed correct results , t here is reason to
think t ha t the a r i thmetic opera tors a re basica l ly correct a nd concentra te on
th e different w a y th e operat ors a re ca lled from th e function power(). The
multiplication of semi *= semiis the ca use of th e problem.
When a reference par a meter is used, t he comput er passes only a
reference to the locat ion of th e actua l para meter (or a rgument )11r a ther
tha n t he value of the a rgument. This mecha nism a llows the va lue of the
a rgum ent t o be cha nged by th e function. When a call is made t o a function
with the sa me a rgument pa ssed t o two or more reference para meters,
errors can occur. In t his case, t he call
semi *= semi;
means t ha t in t he body of operator *=th e values *thisand rhsw ill refer t o
th e sa me memory loca tion, i .e., semi. The diagr a m below sh ow s how t his
ca n ha ppen.
BigInt operator *= (const BigInt & rhs)
{
. . .
*this *= 10;
. . .
}
BigInt semi;
semi *= semi;
11Argument is a sy nonym for actua l para meter wha t is passed to a function. The term formal
parameteris used for the par ameter w ithin the funct ion a s opposed to wha t is passed. Rather t han
use the adjectives forma l and a ctual to modifier para meter, ma ny people use argum ent for wha t is
passed and para meter for wh at is used within t he funct ion.
-
8/10/2019 Large number.pdf
49/10243
We will be una ble to modify th e va lue of *this(e.g., by m ult iplying by 10),
w ithout a lso modifying rhssince th ey sha re th e sam e vector of digits.
Different t est progra ms ma y yield even more bizarr e results.
This problem is called al iasing, a word used whenever there are
tw o or m ore w a ys t o refer to a single memory loca tion. We need a middleroad betw een using r eference par a meters a nd m a king no local copies
w hich lea ds to th e errors w eve just encount ered, and using va lue
para meters which ma ke loca l copies, but lea d t o wa sted memory a nd
tim e. We choose to use reference pa ra met ers, a nd t o ma ke local copies
explicitly when necessary.
In operator *= (const BigInt & big), for exam ple, w e will need to ma ke
a local copy of *this(th e number on t he left of *= in a ca l l such a s x *= y)
a nd u se th e copy. Sin ce w ell use a copy, ma nipula tions of th e copy w ill not
inadvertently chan ge the va lue of rhs(an d vice versa .) Well a lso need t o
check the problem of subtra cting a va lue from it self, i .e., x = x. We m odify
a ddition a nd subtra ction operat ors t o handle th is problem w ithout ma king
a copy, but by convert ing x += xint o x *= 2a nd converting x = xinto x = 0.
For more genera l mult iplica tion w e will ma ke a copy of *thisa nd use the
copy rat her tha n *this.
Alia sing ca nn ot occur in t he I/O funct ions sin ce they h a ve only one
BigIntpara meter.
Fixing operator *=
To elimina te t he a lias ing problem in operator *=we ma ke a copy as shown.
const BigInt & BigInt::operator *=(const BigInt & rhs)
// postcondition: returns value of bigint *rhs after
// multiplication
{
// uses standard "grade school method" for multiplying
if (IsNegative() != rhs.IsNegative())
{
mySign = negative;
}
else
{
mySign = positive;
}
-
8/10/2019 Large number.pdf
50/10244
BigInt self(*this); // copy of self
BigInt sum(0); // to accumulate sum
int k;
int len = rhs.NumDigits(); // # digits in multiplier
for(k=0; k < len; k++)
{
sum += self *rhs.GetDigit(k); // k-th digit *self
self *= 10; // add a zero
}
*this = sum;
return *this;
}
We then ma nipulat e the selflocal var ia ble ra ther t ha n t he implici t
parameter
*this(reca ll tha t
*thisis th e value on th e left, e.g., x in x
*= y.) We
ca n construct a BigIntfrom a nother BigIntbecause the compiler implements
th is const ruct or for us. The const ruct or works correctly beca use ea ch
privat e da ta field is eith er a built-in ty pe or ha s a const ructor defined for
i t as wi th the apvectorclass. C omplete code for a ll the a rith metic operat ors
is given in Appendix C. C ode for t he BigIntcla ss tha t does not f ix a l ia sing is
given in Appendix D .
Conversion Functions
The constructor with a n int para meter a nd t he constructor w ith a str ingpar a meter a re effectively conversion functions from int s a nd st rings,
respectively, t o a corresponding BigIntva lue. It w ould be useful to convert
in t he other direction: from a BigIntto a n int , double, or st ring. The funct ion
ToString()wh ich weve a lrea dy discussed is such a funct ion. Well discuss
conversion fu nctions ToInt()and ToDouble()in t his section.
ToInt():This function converts a BigIntto a n int , its prototype follow s.
int BigInt::ToInt() const
// precondition: INT_MIN
-
8/10/2019 Large number.pdf
51/10245
456 requires t hree st eps: process t he 4, process t he 5, a nd process t he 6.
After ea ch step t he int eger result ha s t he va lues 4, 45, a nd 456 respectively.
B efore an y BigIntdigits ha ve been processed, t he int result sh ould be zero.
This lea ds t o th e code below.
int result = 0;
int k;
for(k=NumDigits()-1; k >= 0; k--)
{
result = result * 10 + GetDigit(k);
}
Were now faced w ith a difficult design decision: w ha t should ha ppen
if the BigIntbeing convert ed exceeds INT_MAX? Sin ce the precondition for
ToInt()s ta tes tha t the va lue being converted should be less tha n or equal
t o INT_MAX, w e could decide not t o dea l wit h t he problem a t a ll . The
postcondition w ould st ill be true w henever th e precondit ion is sa tisfied.
ToInt()might crash , return a va lue of 0, or simply never retur n if the
precondition isnt sa tisfied. Inst ead well w rite code th a t checks for
va lues tha t viola te t he precondition a nd convert t hem t o th e closest
va lue. Altern a tively, w e could print a n error m essa ge. Well include
th e code below in ToInt().
if (INT_MAX < *this) return INT_MAX;
if (*this < INT_MIN) return INT_MIN;
ToDouble():This code is ident ical t o the ToInt()function except th a t
it return s a double.
All of th e BigIntfunctions, including the conversion functions,
a re shown in Appendix C . A brief testing progra m, testconv.cppfor t he
ToDouble()and ToInt()fun ctions is included in Appendix E.
-
8/10/2019 Large number.pdf
52/10246
Study Questions
1. To a void ca l ling ToInt()w i th BigIntvalues th a t exceed INT_MAX, it s
possible to convert th e BigIntvalue to a doubleva lue and compare
double