Você está na página 1de 13

Line Drawing, Leap Years, and Euclid

MITCHELL A. HARRIS
Technical University of Dresden

AND

EDWARD M. REINGOLD
Illinois Institute of Technology

Abstract. Bresenham’s algorithm minimizes error in drawing lines on integer grid


points; leap year calculations, surprisingly, are a generalization. We compare the two
calculations, explicate the pattern, and discuss the connection of the leap year/line
pattern with integer division and Euclid’s algorithm for computing the greatest
common divisor.

Categories and Subject Descriptors: F.2.1 [Analysis of Algorithms and Problem


Complexity]: Numerical Algorithms and Problems—Number-theoretic computations
(e.g., factoring, primality testing); I.3.3 [Computer Graphics]: Picture/Image
Generation; J.2 [Physical Sciences and Engineering]: Astronomy; Mathematics and
statistics
General Terms: Algorithms, Theory
Additional Key Words and Phrases: Bresenham’s algorithm, calendar algorithms,
continued fractions, Euclid’s algorithm, greatest common divisor, leap years, line
drawing, scan-line conversion

1. INTRODUCTION that is discrete with as little error as pos-


sible), speed (it uses only integer arith-
Bresenham’s algorithm [Bresenham 1965] metic), and parsimony (as few pixels as
is the classic technique for plotting lines on possible are used to ensure adjacency).
bitmaps: it approximates linear segments In a very different domain, leap year cal-
defined by rational coefficients using only culations [Reingold and Dershowitz 2001]
integral points. The algorithm calculates involve a similar mapping from the con-
a finite set of points on the integer lat- tinuous to the discrete. By astronomical
tice with minimum total vertical distance observation, one can calculate the ratio
from the original line segment. The essen- between the duration of the revolution
tial design features of the algorithm are of the earth around the sun (the year),
minimization of error (it converts a line and the duration of the rotation of the
segment from a continuous domain to one earth (the day); there are approximately

Authors’ addresses: M. A. Harris, Department of Computer Science, Technical University of Dresden, D-


01062 Dresden, Germany; email: harris@tcs.inf.tu-dresden.de; E. M. Reingold, Department of Computer
Science, Illinois Institute of Technology, Stuart Building, 10 West 31st Street, Suite 236, Chicago, IL 60616-
2987; email: reingold@iit.edu.
Permission to make digital/hard copy of part or all of this work for personal or classroom use is granted
without fee provided that the copies are not made or distributed for profit or commercial advantage, the
copyright notice, the title of the publication, and its date appear, and notice is given that copying is by
permission of ACM, Inc. To copy otherwise, to republish, to post on servers, or to redistribute to lists requires
prior specific permission and/or a fee.
°2004
c ACM 0360-0300/04/0300-0068 $5.00

ACM Computing Surveys, Vol. 36, No. 1, March 2004, pp. 68–80.
Line Drawing, Leap Years, and Euclid 69

365.25 days per year. But calendars, by de- the integer ending point (xE , y E ) of a line
sign, require an integral number of days segment. The basic algorithm calculates
per year; to account for the extra quar- the slope of the line,
ter of a day, we occasionally add an ex-
tra day to the year. Arithmetical calen- 1y yE − yS
dars such as the Julian and the Jewish, = .
1x xE − xS
and the common arithmetical approxima-
tion to the Islamic calendar, have special
formulæ for specifying exactly which years For simplicity we assume that 0 < 1 y ≤
get extra days; these calendars add extra 1x 6= 0: if either 1x = 0 or 1 y = 0, the
days as evenly as possible over the course line drawing is trivial; if 1 y > 1x, we
of years—we will see what “evenly” means merely interchange the x and y axes. To
in the discussion of calendars in Section 2. draw the line segment, we want to darken
How are the line segment and the leap the xE − xS + 1 pixels specified by
year calculations related? It turns out that
µ ¶
Bresenham’s algorithm computes a spe- 1y
cial case of leap year calculations. They y = y S + round (x − xS ) ,
1x
are both computing approximations to
a line with rational slope using integer x = xS , xS + 1, . . . , xE . (1)
division. Both the repeating pattern of
dots in a rasterized line segment and Traditionally, this sequence of pixels is
the repeating pattern of leap years can encoded as a sequence of the plotter con-
be computed using integer division—and trols “east” and “northeast.” We prefer to
they are intimately related to Euclid’s separate the changes of x and y into just
algorithm for calculating greatest com- “east” and “north” movements.
mon divisors and continued fractions. Not We start with (x, y) = (xS , y S ), and cal-
surprisingly, others have noticed simi- culate the sequence of pixels incremen-
larities among these three areas. The tally, repeatedly adding 1 to x, and oc-
connection between astronomical cycles casionally adding 1 to y. We make the
and greatest common divisors is folkloric decision to increment y by keeping track
[Rockett and Szüsz 1992], going even back of the error ², the vertical distance of the
to the Greeks. More recently, Brons [1974], pixel to the true line segment. If ² ≥ 1/2,
Castle and Pitteway [1987], Pitteway the pixel above more closely approximates
[1985], and Troesch [1998] all discussed the true value of y, so we increment y by
the connection between line drawing and 1 and decrement ² by 1. Otherwise, we add
Euclid’s algorithm. Here we give explicit the slope 1 y/1x (which is between 0 and
correspondences among all three. First, 1 by assumption) to ² and do not change
we discuss the details of each domain, and y. The initial error is ² = 0 and this al-
then compare them. gorithm minimizes the total vertical error
of the pixels to the real line, since induc-
2. LINE DRAWING
tively the error ² is always in the range
[−1/2, 1/2], the best possible on the in-
In this section we derive Bresenham’s line teger lattice. This algorithm is shown in
drawing algorithm, one of the fundamen- Algorithm 1(a); it computes the points
tal algorithms of computer graphics. In its given by Equation (1).
final form, as usually presented, the algo- Algorithm 1(a) can easily be restricted
rithm is obscure; deriving it in a step-by- to integer operations—calculate the (ra-
step way is both interesting and illuminat- tional) slope 1x/1 y in lowest common
ing. Furthermore, it is much easier to deal terms, so that 1x and 1 y are relatively
with the simpler initial form than with the prime, and multiply all assignments and
equivalent final form. tests involving ² by 21x; for convenience
A line drawing algorithm has as its in- we also shift the range of ² from [−1x, 1x]
put the integer starting point (xS , y S ) and to [0, 21x]; the result is Algorithm 1(b).

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


70 Harris and Reingold

Algorigthm 1. Transformations leading to Bresenham’s algorithm. Version (a) uses floating point operations,
eliminated in version (b) by multiplying through by 21x and shifting the resulting range of ² from [−1x, 1x)
to [0, 21x); version (c) results from then moving the update of the error to after the comparison, shifting the
initial value of ², and using a zero test in the if.

This algorithm can be converted, in turn, Because of the manner in which x and y
to the traditional Bresenham algorithm of are incremented, every x coordinate and
Algorithm 1(c) by moving the update of the every y coordinate between the endpoints
error after the comparison, shifting the occurs in a Bresenham line. All such lines
initial value of ², and using a “zero test” are made of horizontal segments of length
(this simpler test is the point of the trans- one or more; the lengths of the segments
formation). Each of these transformations in a particular Bresenham line have no
preserves correctness. more than two distinct values, excluding
Examining Algorithm 1(c), we see that the segments touching the endpoints. If
y is incremented by 1 only when ² is decre- 1 y = 1, then the line has a uniform ap-
mented by 21x, making y the quotient on pearance, with a single length for the seg-
division by 21x, with remainder ². Hence, ments. For 1 y > 1, the pattern of alter-
the equation plotted by the algorithm cor- nating long and short sequences appears
responds to Equation (1): to have some pattern but it is difficult
to determine by inspection. Changing the
¹ º initial value of ² does not change the basic
2n1 y + ²0
yn = yS + pattern, but shifts it.
21x Bresenham’s original paper [1965] es-
¹ º sentially gives Algorithm 1(c) directly
2(xn − xS )1 y + 1x
= yS + , (2) from an analysis of error. Sproull [1982]
21x
derived Bresenham’s algorithm as we do,
starting with the straightforward naı̈ve
Since at every step an increment is made algorithm, using rationals and trans-
to x, and possibly to y, the resulting line formed it step by step into Bresenham’s
drawing is “connected” in that successive by scaling and shifting. Berstel [1990]
points are adjacent horizontally or diag- described the Bresenham patterns us-
onally. As an example, three lines with ing formal language theory; these pat-
different right endpoints are shown in terns are an instance of Sturmian
Figure 1. Note the simple pattern for the words—see Allouche and Shallit [2003],
line from (0, 0) to (30, 10) in Figure 1(a) Section 9.2.
and the more complicated patterns for
lines from (0, 0) to (30, 11) and (30, 12) in 3. LEAP YEARS
Figures 1(b) and 1(c), respectively.
We call a set of points generated by Humans observed millennia ago that
Bresenham’s algorithm a Bresenham line. there are approximately 365.25 days

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


Line Drawing, Leap Years, and Euclid 71

Fig. 1. Three examples of lines and their approximation by points using Bresenham’s algo-
rithm; the circled lattice points in a plot constitute the “Bresenham line” approximating the
dashed line shown.

between successive winter solstices; hence year if and only if y ≡ 0 (mod 4), and
there are nearly 1461 days for every to the Coptic/Ethiopic rule that year y
4 years. Since 1461 − 365 × 4 = 1, it is a leap year if and only if y ≡ 3
takes 4 years for the extra quarter of a (mod 4). The given ratio of 1461 days
day to add up to a full day, so an extra every 4 years gives an average year
day must be added every four years. This length of 365.25 days per year, achieved
corresponds to the (old style) Julian cal- with an integral number of days per
endar leap year rule: year y is a leap year.

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


72 Harris and Reingold

But an average of 365.25 days per year In our presentation below, we use this
is not fully accurate. The true average arithmetical approximation to the Islamic
(which is changing very slowly over time) calendar as the canonical example since
is closer to 365.242 days per year and it displays more of the depth and gen-
that small difference accumulates into an erality of the derivation than does the
error of about one day every 125 years. Julian.
By the sixteenth century the error had The task of a calendar leap year rule is
caused the spring equinox to shift from to spread the leap years as evenly as possi-
its traditional (Roman) date of March 21 ble over the cycle of years. We assume that
to around March 11; if uncorrected, this, the physical parameters never change and
in turn, would cause the date of Easter that there is at least one day per year.
(which depends on the equinox) to migrate Given a ratio of x days in c years, where
through the seasons. Pope Gregory XIII x and c are positive integers, c ≤ x, we
reset the calendar by 10 days, refined seek an even distribution of leap years.
the definition of the date of Easter, and The length in days of a normal year is
changed the leap year rule to omit leap L = bx/cc, and a leap year has L + 1
days in century years not divisible by days. If c divides x evenly, no leap years
400. A more thorough discussion can are needed; otherwise,
be found in Reingold and Dershowitz
[2001], which also gives extensive x = cL + l ,
references.
The leap year rule for the Gregorian cal- where 0 < l < c are integers; l is the num-
endar (our present calendar) is that leap ber of leap years that must occur in a cycle
years are those divisible by 4, except not every c years starting with year 0. So, we
those divisible by 100, except those divisi- insist that a year be a leap year if its num-
ble by 400. This rule gives an average year ber has reached or just passed an integral
length of 365 + 1/4 − 1/100 + 1/400 = multiple of the ratio c/l ; that is, year y is
36597/400 = 365.2425 days. See Shallit the kth leap year (with year 0 as the first
[1994] for a discussion of the mathemat- leap year) if
ics of Gregorian-like leap year rules. The
Gregorian rule more closely approximates c c
(k − 1) ≤ y < (k − 1) + 1, (3)
the astronomical average in the long run, l l
but with a more significant deviation from
that average (see below). that is, if
Other calendars use different ratios and
so have different leap year rules. In the (k − 1)c ≤ ly < (k − 1)c + l
Islamic calendar, a year is defined as the
passage of twelve lunations (times be- or
tween successive new moons) [Reingold
ly mod c < l . (4)
and Dershowitz 2001]. This results in ap-
proximately 354 11 days per year or about We can also generalize this by insisting
30
10631 days every 30 years. Since 10631 − that year 0 be in position s of the leap year
354 × 30 = 11, we need 11 leap years in pattern; we shift:
every 30-year cycle. The common arith-
metical approximation to the Islamic cal- l ( y + s) mod c < l . (5)
endar has leap years in the 2nd, 5th, 7th,
10th, 13th, 16th, 18th, 21st, 24th, 26th, In the arithmetical approximation to the
and 29th years of the cycle. There is an Islamic calendar,
arithmetical rule for this selection but it
is not obvious: the year y is a leap year 11( y + 4) mod 30 < 11,
if and only if ((11 y + 14) mod 30) < 11.
Though this seems arbitrary, the formula which is inequality (5) with s = 4. In-
follows from the ratio of years to days. equality (5) also works for the cycle of

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


Line Drawing, Leap Years, and Euclid 73

Hebrew months and years, as well as ranged to give


Julian, Coptic, and Ethiopic leap years ¹ º
(see Reingold and Dershowitz [2001]). It y
does not work for the Gregorian leap years, k= + 1. (6)
c/l
though it does apply to the positions of
long (31-day) months versus short months
Using this formula, we find the number of
on the Gregorian calendar—see Reingold
days x in the years in the range [0 · · · y] is
and Dershowitz [2001].
The notion of “even distribution” here
should be contrasted with the division x = L( y + 1)
¹ º
into “as-equal-as-possible parts” given in l ( y + 1) + ((l (s − 1)) mod c)
+ ; (7)
Graham et al. [1994], Equation 3.24, to di- c
vide lines of text into balanced columns.
Translating their division into the leap this sums L days for each of the y +1 years
year setting, the cL + l days would be di- and an extra day for each leap year (see
vided into c years as Reingold and Dershowitz [2001]). For ex-
» ¼ » ¼ ample, the number of days in years 0, 1,
cL + l cL + l − 1 2, 3, 4 (or the number of the first day of
cL + l = + + ···
c c year 5) in the arithmetical approximation
» ¼ to the Islamic calendar (with s = 4) is
cL + l − c + 1
+ , ¹ º
c 11 × 5 + ((11 × 3) mod 30)
354 × 5 +
putting all the leap years at the start of the 30
cycle. On the other hand, comparing the = 1770 + b58/30c = 1771,
leap year placement of the Gregorian cal-
endar with that of the Julian calendar— where year 2 is a leap year and both years
inequality (5) with l = 1, c = 4, s = and days are numbered starting from 0.
0—we find the year-by-year error in the We can also go the other direction, find-
Julian calendar cycles through the val- ing the year at a particular day num-
ues 0, 1/4, 1/2, 3/4. The corresponding ber. A derivation similar to the above
cycle of errors for the Gregorian calen- is followed; the details can be found in
dar is 0, 97/400, 2 × 97/400, 3 × 97/400, Reingold and Dershowitz [2001], Sec-
4 × 97/400 − 1 = −3/100, . . . ; these er- tion 1.12. We find that
rors range from −18/25 at year 96 to
591/400 at year 303. The Gregorian wob- y = yS
ble around its average is thus 591/400 + ¹ º
c(x − xS ) − ((ls − l ) mod c) + c − 1
18/25 = 879/400, almost 2.2 days com- + ,
pared to Julian calendar’s wobble of 0.75 cL + l
days around its average. We want the leap (8)
years distributed as uniformly through-
out the cycle so the range of errors is where xS is the day number we specify
minimized. must begin year number y S . Contrary to
So far we have just considered years. the convention used here, Reingold and
We also want to find relationships between Dershowitz [2001] require that the first
days and years. Just as we label the years day of year 1 (as opposed to year 0) be
0, 1, 2, . . . , so we label days 0, 1, 2, . . . , numbered day 0; this makes our functions
with day 0 being the first day of year 0. shifted versions of theirs. For example,
For example, how many days are there in Equation (8), we achieve this by let-
in the range of years 0 · · · y? To compute ting y S = 1 and xS = L (our day num-
this, we need to know the number of leap ber for the first day of our year 1) which
years k in the range of years 0 · · · y. For yields Equation (1.64) from Reingold and
the case s = 0, inequality (3) can be rear- Dershowitz [2001].

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


74 Harris and Reingold

Fig. 2. Points of the leap year line for 1 y/1x = 11/30, s = 0. The jumps between steps
give the leap year placement; the dashed line shows the line being approximated.

4. COMPARING THE CALCULATIONS in terms of 1x and 1 y,


Let y stand for a year number and x for a
day number; we want to assign y values y = yS
¹ º
to x values, that is, determine in what 1 y(x − xS ) − ((ls − l ) mod 1 y) + 1 y − 1
year a particular day falls. If day x falls + .
1x
within year y, we darken the pixel (x, y).
(9)
The days are labeled sequentially, and no
day is in two different years, so we have
the same connectedness as Bresenham We call a set of (day, year) points deter-
lines. A set of days in the same year mined by the ratio 1 y/1x and the shift s a
forms a contiguous sequence of pixels at leap year line (whether it actually has leap
the same y-coordinate and the lengths years or not). Figure 2 shows the leap year
of these sequences vary between two dis- line for 1 y/1x = 11/30, s = 0. For the
tinct lengths, L and L + 1, following the same ratio, a Bresenham line and a leap
leap year pattern. In essence, this map- year line have the same pattern, but they
ping from days to years is a set of inte- can be shifted differently. A Bresenham
gral lattice points approximating a line for line has first and last segments close to
which the slope is the exact ratio of years half the average line segment length, but a
to days. Thus we form a correspondence leap year line has arbitrary end segments
of days and years with grid points and depending on the shift—compare the leap
an approximation to a line by those grid year line in Figure 2 to the Bresenham
points; the number cL + l of days in a cy- line in Figure 1(b). When s = 0, the leap
cle is the run 1x, the number c of years year line spreads the two type of segments
in a cycle is the rise 1 y, and the aver- (common years are segments of length L
age year length L̄ is 1x/1 y, the recipro- and leap years are segments of length
cal of the slope. The number of leap years L + 1) evenly.
l in the run 1x is 1x mod 1 y. Hence leap To show now that Bresenham lines are
years can be viewed as discretizations of specific cases of leap year lines, we find a
lines with rational slopes; we must show leap year line whose shift s depends on the
the Bresenham line is a special case of the endpoints of the Bresenham line. Assum-
leap year calculation—we do so by show- ing, as we do for Bresenham lines, that the
ing that Equation (2) is a special case of slope is between 0 and 1, we want to solve
Equation (8). for s such that Equations (2) and (9) are
Inspecting the quotients in equations (2) equal. Comparing equations, and replac-
and (8), and using the fact that the exact ing l and c as needed, we find that
average year length L̄ = L +l /c is also the
reciprocal of the slope, we can rewrite (8) 1x = 2(1 y − (l (s − 1) mod 1 y) − 1).

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


Line Drawing, Leap Years, and Euclid 75

Table I. Summary of Comparison Between Leap Years and Bresenham Lines


(The parameters of the calendar formulas are c, L, l < c, and s; the parameters of the Bresenham line are
xS , yS , xE , and yE .)
Calendar formula/ Approximate Islamic
Calendar Bresenham line Bresenham formula calendar
Day number x-coordinate Integer x
Year number y-coordinate Integer y
Starting point xS , y S
Ending point xE , y E
Years in leap year Segments in repeating c = 1 y = yE − yE 30
cycle pattern
Days in leap year cycle Pixels in repeating cL + l = 1x = xE − xS 10631
pattern
Ratio of years to days Slope of line c/(cL + l ) = 1 y/1x 30/10631
Leap years per cycle Number of long l = 1x mod 1 y 11
segments
Days in an ordinary Pixels in short segments L = b1x/1 yc 354
year
Days in a leap year Pixels in long segments L + 1 = b1x/1 yc + 1 355
Average year length Average segment length L̄ =j(cL + l )/c = 1x/1
k y 10631/30 = 354 11
30
21 y − 1x − 1
Position of year 1 in s= +1 4
2l
cycle
Initial error 1x
Year y is a leap year yth segment is long l (jy + s) mod c < l k 11( y + 4) mod
j 30 < 11k
ly + ((l (s − 1)) mod c) 11 y + 3
Year y begins on day x Segment begins at (x, y) x = Ly + x = 354 y +
c 30
j k j k
cx − ((l (s − 1)) mod c) + c − 1 30x + 26
Day x is in year y Point (x, y) is on the line y = y=
cL + l 10631

The shift s can thus be 5. THE UNDERLYING PATTERN


$ % For both line drawing and leap years there
21 y−1x−1
+ k1 y are only two parameters that determine
s= 2
+ 1,
l the repeating pattern: 1x and 1 y (as
throughout, we assume 1x ≥ 1 y). If we
for any integer k. Choosing k = 0 gives are only interested in these cycles, we can
restrict ourselves to leap year lines with
¹ º no shift, that is s = 0. As mentioned
21 y − 1x − 1 above with respect to Bresenham’s algo-
s= + 1. (10)
2l rithm, the pattern of alternating normal
and leap segments can be difficult to see
A summary of the comparisons between by inspection. Of course, the pattern is de-
leap year lines and Bresenham lines is termined (implicitly) by equation (8), but
given in Table I. There are a few pecu- equation (8) does not explicitly give the re-
liarities that distinguish Bresenham lines peating pattern. The pattern is intimately
and leap year lines. A Bresenham line is connected with Euclid’s algorithm for com-
defined by its two endpoints; a leap year puting the greatest common divisor of 1x
line by its slope (the ratio), the starting and 1 y.
point, and the shift. The intention of draw- Euclid’s algorithm can be expressed in
ing a Bresenham line is to plot a finite seg- many ways, but the most basic is given
ment; the intention of the leap year line is in as a function EUCLID in Algorithm 2(a),
to give a function for an assignment for in which we use repeated subtraction to
all days, not just a range of days; thus, a get the greatest common divisor. The proof
leap year pattern repeats endlessly, but a that this subtractive algorithm is correct
Bresenham line does not. follows from the invariant relationship

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


76 Harris and Reingold

Algorigthm 2. Subtractive Euclid’s algorithm to compute gcd(u, v), u, v > 0, and a modified version to
compute the leap year pattern. kP kx and kP k y are, respectively, the horizontal and vertical extents of a path
P . Both algorithms take O(u + v) iterations.

Table II. A Trace of MODEUCLID (30, 11) Before the Test in Line 3 is
Executed (2 is an abbreviation for and 3 is an abbreviation
for . Figure 3 shows the resulting pattern)
u v Pl kPl k y /kPl kx Pr kPr k y /kPr kx
30 11 0/1 1/0
19 11 0/1 1/1
8 11 0/1 1/2
8 3 3 1/3 2 1/2
5 3 3 1/3 32 2/5
2 3 3 1/3 332 3/8
2 1 3332 4/11 332 3/8
1 1 3332 4/11 3332 332 7/19
return 3332 3332 332 11/30

given between lines 1 and 2, that the is a rightward movement of the line of
greatest common divisor of u and v at that length 1 and is an upward movement. We
point equals the greatest common divisor use the notations kP kx and kP k y as, re-
of the original parameters to EUCLID. spectively, the horizontal and vertical ex-
We can modify the subtractive Euclid’s tents of a path P ; thus
algorithm, so that it builds up the leap
year pattern by concatenating appropriate kP k y
smaller patterns; the modified algorithm slope(P ) = .
is MODEUCLID in Algorithm 2(b). It com- kP kx
poses paths Pl and Pr that correspond,
respectively, to approximations from be- An example trace of MODEUCLID is shown
low and above the desired slope. We call in Table II. Figure 3 shows the resulting
MODEUCLID with the numerator and de- path.
nominator of that desired slope; the ini- The invariant relationships given be-
tial Pl = and the initial Pr = corre- tween lines 3 and 4 of MODEUCLID are
spond to the slopes 0/1 and 1/0, where the heart of an inductive proof that

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


Line Drawing, Leap Years, and Euclid 77

Fig. 3. The output from MODEUCLID (30, 11). It is an articulated leap year line corresponding
to Figure 2. The dashed line from (0, 0) to (11, 30) touches integral lattice points only at the
endpoints because gcd(11, 30) = 1.

MODEUCLID computes the correct leap year sired. Similarly, to prove that
line. First, we prove that the relationships,
original value of v = u0 kPl0 k y + v0 kPr0 k y ,
original value of u = ukPl kx + vkPr kx ,
(11) we have

original value of v = ukPl k y + vkPr k y , u0 kPl0 k y +v0 kPr0 k y = ukPl Pr k y


(12) + (v − u)kPr k y
= u(kPl k y + kPr k y )
kPl kx kPr k y − kPr kx kPl k y = 1, (13) + (v − u)kPr k y
and = ukPl k y + vkPr k y ,

slope(Pl ) < slope(Pr ) (14) which, by induction, is the original value


hold from iteration to iteration; they are of v. Finally, to prove that (13) holds from
clearly true at the first iteration. If u < v iteration to iteration,
in line 4, then we set v := v−u in line 5 and
Pl := Pl Pr in line 6. Let us refer to values kPl0 kx kPr0 k y −kPr0 kx kPl0 k y
at the next moment we are between lines = kPl Pr kx kPr k y − kPr kx kPl Pr ky
3 and 4 by appending primes to them; thus = (kPl kx +kPr kx )kPr k y − kPr kx
we must prove that
× (kPl k y +kPr k y ) = kPl kx kPr k y
− kPr kx kPl k y = 1,
original value of u = u0 kPl0 kx + v0 kPr0 kx .
by induction. The proofs for the case u ≥
Expressing this in terms of the old values, v are almost identical. Finally, (14) holds
because (13) guarantees that
u0 kPl0 kx + v0 kPr0 kx = ukPl Pr kx + (v − u)kPr kx
= u(kPl kx + kPr kx ) slope(Pl ) < slope(Pl Pr ) < slope(Pr ).
+ (v − u)kPr kx
Now we use the invariant relation-
= ukPl kx + vkPr kx , ships to prove that the path returned
goes from (0, 0) to the original value of
which, by induction (on the number of it- (u, v) and that it is a leap year line. The
erations), is the original value of u, as de- path returned, (Pl Pr )u , goes from (0, 0) to

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


78 Harris and Reingold

Fig. 4. If Pl is a leap year line from (0, 0) to (kPl kx , kPl k y ), Pr is a leap year line from
(0, 0) to (kPr kx , kPr k y ), and kPl kx kPr k y − kPr kx kPl k y = 1, then the recursive structure
of the leap year line from (0, 0) to (kPl kx + kPr kx , kPl k y + kP k y ) is Pl Pr .

(ukPl kx + ukPr kx , ukPl k y + ukPr k y ), but which would mean that the leap year line
because the loop ends when u = v, from (0, 0) to (kPl Pr kx , kPl Pr k y ) passes
through the same points as Pl for 0 ≤ i ≤
(ukPl kx + ukPr kx , ukPl k y + ukPr k y ) kPl kx . Equation (15) follows from proving
= (ukPl kx + vkPr kx , ukPl k y + vkPr k y ) that if âb − ab̂ = 1 and 0 ≤ i < b, then
= (original value of u, j a k ¹ a + â º
original value of v), i = i . (16)
b b + b̂
by (11) and (12).
A path P is a leap year line if it passes Using the identity
through (i, bikP k y /kPx kc) for each i, 0 ≤
i ≤ kPx k. Initially, the paths Pl and Pr jak a a mod b
are (trivial) leap year lines. To prove that = − ,
b b b
the path returned is a leap year line, we
must show that the recursive structure proposed equation (16) becomes
shown in Figure 4 is correct—that is, that
if Pl is a leap year line from (0, 0) to ai ai mod b
(kPl kx , kPl k y ), Pr is a leap year line from −
(0, 0) to (kPr kx , kPr k y ), and kPl kx kPr k y − b b
kPr kx kPl k y = 1, then Pl Pr is a leap year (a + â)i (a + â)i mod (b + b̂)
= − ,
line from (0, 0) to (kPl kx + kPr kx , kPl k y + b + b̂ b + b̂
kP k y ).
Thus to prove that Pl Pr is a leap year or
line, we must show that it passes through
(i, bikPl Pr k y /kPl Pr kx c) for each i, 0 ≤ i ≤ (a + â)i mod (b + b̂) ai mod b
kPl Pr kx = kPl kx + kPr kx , given that Pl −
b + b̂ b
passes through (i, bikPl k y /kPl kx c) for each
i, 0 ≤ i ≤ kPl kx , and that Pr passes (a + â)i ia
= − .
through (i, bikPr k y /kPr kx c) for each i, 0 ≤ b + b̂ b
i ≤ kPr kx . First, consider the case i, 0 ≤
i ≤ kPl kx . It suffices to show that
Multiplying through by b(b + b̂) and using
¹ º ¹ º âb − ab̂ = 1 transforms this into
kPl k y kPl k y + kPr k y
i = i , (15)
kPl kx kPl kx + kPr kx
b(a + â)i mod b(b + b̂)
that is, − a(b + b̂)i mod b(b + b̂) = i.
¥ ¦ ¥ ¦
slope(Pl )i = slope(Pl Pr )i , Rearranging and again using âb − ab̂ = 1

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


Line Drawing, Leap Years, and Euclid 79

Algorigthm 3. Euclid’s algorithm to compute gcd(u, v), u, v ≥ 0, and a modified version


to compute the leap year pattern. The loop invariants (not shown) are identical to those
in Algorithm 2. By Lamé’s theorem these algorithms take O(log max(u, v)) iterations.

Table III. A Trace of MODEUCLID0 (30, 11) Before the Test in Line 5 is Executed
u v Pl kPl k y /kPl kx Pr kPr k y /kPr kx
30 11 0/1 1/0
8 11 0/1 =2 1/2
8 3 3 1/3 2 1/2
2 3 3 1/3 332 3/8
2 1 3332 4/11 332 3/8
0 1 3332 4/11 3332 3332 332 11/30
return 3332 3332 332 11/30

makes this into To prove that Pl Pr passes through


(i, bikPl Pr k y /kPl Pr kx c) for each i, kPl kx <
[a(b + b̂) + 1]i mod b(b + b̂) i ≤ kPr kx + kPr kx is similar, but uses
= i + a(b + b̂)i mod b(b + b̂), ¹ º ¹ º
â a + â
a+ (i − b) = i , (17)
which is true provided that b̂ b + b̂

i + a(b + b̂)i mod b(b + b̂) < b(b + b̂), given âb−ab̂ = 1 and b ≤ i ≤ b+ b̂. A proof
of (17) parallels our proof of (16). It follows
that is, if that MODEUCLID computes the appropriate
leap year line.
a(b + b̂)i mod b(b + b̂) < b(b + b̂) − i. Of course, we do not need to do re-
peated subtraction in Euclid’s algorithm—
Dividing this inequality by b + b̂ trans- we can rewrite it in its more common
forms it to form by using the modulus function to
group repeated subtractions into a sin-
i gle operation. Doing so yields EUCLID0 ,
ai mod b < b − ,
b + b̂ given in Algorithm 3(a). We can simi-
larly rewrite MODEUCLID; the result is
which holds because i ≤ b insures that i < MODEUCLID0 , shown as Algorithm 3(b).
b + b̂. Thus (16), and hence (15), hold. Table III given the trace of MODEUCLID0

ACM Computing Surveys, Vol. 36, No. 1, March 2004.


80 Harris and Reingold

(30, 11) corresponding to that shown in BERSTEL, J. 1990. Tracé de droites, fractions con-
Table II. tinues et morphismes itérés. In Mots: Mélanges
Offerts à M.-P. Schützenberger, M. Lothaire,
Good practice dictates that we not give Ed. Editions Hermès, Paris, France, 298–
an algorithm without discussing its run- 309.
ning time. The subtractive EUCLID (and BRESENHAM, J. E. 1965. Algorithm for computer
hence also MODEUCLID) take time O(u + v). control of a digital plotter. IBM Syst. J. 4, 1, 25–
From Lamé’s theorem we know that the 30.
worst case of the gcd-form of Euclid’s algo- BRONS, R. 1974. Linguistic methods for the de-
scription of a straight line on a grid. Comput.
rithm is a pair of adjacent Fibonacci num- Graph. Image Process. 3, 1, 48–62.
bers u = Fi+1 and v = Fi , causing i itera- CASTLE, C. M. A. AND PITTEWAY, M. L. V. 1987.
tions (see Knuth [1998], Theorem F, page An efficient structural technique for encoding
360). EUCLID0 thus takes O(log max(u, v)) ‘best-fit’ straight lines. Comput. J. 30, 2, 168–
iterations, as does MODEUCLID0 . 175.
FRAENKEL, A. S., MUSHKIN, M., AND TASSA, U.
6. CONCLUSIONS 1978. Determination of [nθ ] by its sequence
of differences. Can. Math. Bull. 21, 441–
The pattern of a Bresenham line is a spe- 446.
cial case of a leap year rule, and both GRAHAM, R. L., KNUTH, D. E., AND PATASHNIK, O. 1994.
are described by Euclid’s algorithm, as Concrete Mathematics, 2nd ed. Addison-Wesley,
adapted in Algorithm 3. The trace of Reading, MA.
Algorithm 3 in Table III suggests that the KNUTH, D. E. 1998. The Art of Computer Pro-
gramming (Volume 2: Seminumerical Algo-
slopes of the paths Pl and Pr are the con- rithms), 3rd ed. Addison-Wesley, Reading,
tinuants of the continued fraction expan- MA.
sion of v/u; this is indeed the case. Thus PITTEWAY, M. L. V. 1985. The relationship be-
our discussion can be tied to continued tween Euclid’s algorithm and run-length encod-
fractions and many other applications of ing. In Fundamental Algorithms for Computer
Euclid’s algorithm such as finding paths in Graphics, R. A. Earnshaw, Ed. Springer, Berlin,
Germany, 105–111.
the Stern-Brocot tree or finding the short-
REINGOLD, E. M. AND DERSHOWITZ, N. 2001. Cal-
est factorization in elementary matrices of endrical Calculations: The Millennium Edi-
a 2 × 2 integer matrix with determinant tion. Cambridge University Press, Cambridge,
1 (see [Graham et al. 1994, Section 6.7]). U.K.
Both line drawing and leap year calcula- ROCKETT, A. M. AND SZÜSZ, P. 1992. Continued Frac-
tions are essentially computing bαx + βc, tions. World Scientific, Singapore.
for rational α and β, and are thus also re- SHALLIT, J. 1994. Pierce expansions and rules for
the determination of leap years. Fibonacci
lated to the Beatty sequences [Fraenkel Quart. 32, 5, 416–423.
et al. 1978]. SPROULL, R. F. 1982. Using program transforma-
REFERENCES tions to derive line-drawing algorithms. ACM
Trans. Graph. 1, 4, 259–273.
ALLOUCHE, J.-P. AND SHALLIT, J. 2003. Automatic TROESCH, A. 1998. Droites discrètes et calendriers.
Sequences. Cambridge University Press, Cam- Math. Inform. et Sci. Humaines 141, 36, 11–
bridge, U.K. 41.

Received June 2003; accepted April 2004

ACM Computing Surveys, Vol. 36, No. 1, March 2004.

Você também pode gostar