136 CHAPTER8. CONTROLSTRUCTURES,PART 2
- A postive wholenumbern 2 is primeif nonumberbetween2 and n(inclusive)evenlydividesn.
Writea programthatacceptsa valueofnasinputanddeterminesif thevalueis prime. Ifnisnot
prime,yourprogramshouldquitassoonasit findsa valuethatevenlydividesn.
- Modifythepreviousprogramtofindeveryprimenumberlessthanorequalton.
- Thegreatestcommondivisor(GCD)oftwo valuescanbecomputedusingEuclid’s algorithm.Starting
withthevaluesmandn, werepeatedlyapplytheformula:n, m = m, n%muntilmis 0.Atthat
point,nis theGCDoftheoriginalmandn. Writea programthatfindstheGCDoftwo numbersusing
thisalgorithm.
- Writea programthatcomputesthefuelefficiency ofa multi-leg journey. Theprogramwillfirstprompt
forthestartingodometerreadingandthengetinformationabouta seriesoflegs. Foreachleg,the
userentersthecurrentodometerreadingandtheamountofgasused(separatedbya space).Theuser
signalstheendofthetripwitha blankline.Theprogramshouldprintoutthemilespergallonachieved
oneachleg andthetotalMPGforthetrip.
- Modifythepreviousprogramtogetitsinputfroma file.
- Heatingandcoolingdegree-daysaremeasuresusedbyutilitycompaniestoestimateenergyrequire-
ments.If theaveragetemperaturefora dayis below 60,thenthenumberofdegreesbelow 60is added
totheheatingdegree-days.If thetemperatureis above 80,theamountover 80 is addedtothecooling
degree-days.Writea programthatacceptsa sequenceofaveragedailytempsandcomputestherunning
totalofcoolingandheatingdegree-days.Theprogramshouldprintthesetwo totalsafterallthedata
hasbeenprocessed.
- Modifythepreviousprogramtogetitsinputfroma file.
- Writea programthatgraphicallyplotsa regressionline,thatis,thelinewiththebestfitthrougha
collectionofpoints. Firstasktheusertospecifythedatapointsbyclickingonthemina graphics
window. To findtheendofinput,placea smallrectanglelabelled“Done”inthelowerleftcornerof
thewindow;theprogramwillstopgatheringpointswhentheuserclicksinsidethatrectangle.
Theregressionlineis thelinewiththefollowingequation:
y ̄y m
x ̄x
where
m
∑xiyi n ̄x ̄y
∑x^2 i n ̄x^2
̄xis themeanofthex-valuesand ̄yis themeanofthey-values.
Astheuserclicksonpoints,theprogramshoulddraw theminthegraphicswindow andkeeptrackof
thecountofinputvaluesandtherunningsumofx,y,x^2 andxyvalues.Whentheuserclicksinsidethe
“Done”rectangle,theprogramthencomputesvalueofy(usingtheequationsabove)correpondingto
thexvaluesattheleftandrightedgesofthewindow tocomputetheendpointsoftheregressionline
spanningthewindow. Afterthelineis drawn,theprogramwillpauseforanothermouseclickbefore
closingthewindow andquitting.