C++大学教程课后习题答案13.pdf
《C++大学教程课后习题答案13.pdf》由会员分享,可在线阅读,更多相关《C++大学教程课后习题答案13.pdf(37页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、Chapter 14RECURSION1.Solutions to and Remarks on Selected Programming Assignments1.Fibonacci NumbersThese solutions have been tested under two Linux versions using two versions of g+,under Windows XP with VC+6.0 and Borland 5.0.The full recursive version is slow.Ittakes about 17 seconds for 1 comput
2、ation of Fib 1(35)on an older,very slow machine(i486DX2/100,16 MB RAM).On a more modem machine(1 GHz Athlon.266 MHz front sidebus,512 MB DDR RAM,fast disk drives)it runs a bit faster:N=35 takes 3 seconds,N=40 takes about 30 seconds,N=41 about 50 seconds,and N=42 takes 80 seconds.A valueof N greater
3、than 47 results in integer overflow and incorrect results with all the compilersmentioned above.With most implementations,long in t is a type the same size as in t.Because there area few implementations that provide a long in t that is longer than an in t,I used long asthe argument and return types
4、for the fib function.To get Fibonacci numbers up to N=50 for checking the results of the program,I changedthe long type in the recursive function to long long(a 19 digit integer type supportedby GNU g+,but not ANSI/ISO C+).I compiled this using g+-3.0 under the DebianLinux 3.0 operating system on a
5、K6-2/350 with a 100 MHz backplane and 400K RAM.Onthis somewhat slow machine,this version of the program took about two hours for N=50,giving presumably correct results.(I acknowledge that I did not look them up.)The resultsagree with the code with a long return and long parameter type up to N=47.Thi
6、s function computes and discards too many of the Fibonacci numbers.This kind ofrecursion is called umbrella recursion*because it spreads like an umbrella,recomputingvalues many times.1Copyright 2008 Pearson Education,Inc.Publishing as Pearson Addison-Wesley/File:chl4prglFibonacci.cc/Chapter 14,Progr
7、amming Problem#1/Write a recursive function for a function having one/parameter that generates the nth Fibonacci number.#include#include/This is the full recursive version.unsigned long Fibl(int n)if(n=0|n=1)return 1;return Fibl(n-1)+Fibl(n-2);)int main()using namespace std;cihar ans;dntoNcout 工 wil
8、l display fibonacci numbers 0-N.n;cout N;for(int i=0;icout Fibl(i)cout ans;while(Y*=ansreturn 0;N;i+)endl;continue,I I y=anything else quitsll;ans);2.Recursive Index of SmallestCAUTIONS:Please warn the student that number_used is NOT the largest index used,rather itis the number of elements.This was
9、 my hardest-to-find-error in coding this.I also recommend that the student remove theSort function from Display 10-12.Including Sort obscures the behavior of thein d e x _ o f_ sm allest.I had it finding the maximum,but I didnt spot that until I removedthe sort routine and its support routines.This
10、is modified from code of the text.I prefer that the student not reinvent the wheel:use.Sheshould reuse code from the texts Displays to advantage!/f i l e:c h l4 p rg 2.cc/T e s ts th e p ro ced u re re c u rs iv e fu n c tio n in d e x _ o f_ sm allest/S o rt ro u tin e removed to sim p lify th e te
11、 s tin g en v iro n m en t.#in clu d e v o id f i l l _ a r r a y(in t a z in t s i z e,int&num ber_used);/P re c o n d itio n:s iz e is th e d e c la re d s iz e of th e a rra y a./P o s tc o n d itio n:num ber_used is th e number of v a lu e s sto re d/i n a 0 th ro u g h anum ber_used-1 have been
12、 f i l l e d w ith/n o n n eg ativ e in te g e rs re a d from th e k ey b o ard.in t in d e x _ o f_ sm a lle st(c o n st in t a zin t s ta r t_ in d e xz in t num ber_used);/NOTE:d e sig n and im p lem en tatio n of th is fu n c tio n a re a t/th e end of th is f i l e./P re c o n d itio n:0=s ta r
13、t_ in d e x num ber_used./R e fe re n c e d a rra y elem ents have v a lu e s./R e tu rn v alu e is th e index i such th a t a i is th e s m a lle st/o f th e v a lu es/a s ta r t_ in d e x ,a s ta rt_ in d e x +1 ,.,anum ber_used-1.in t m ain()u sin g nam espace s t d;cout This program tests recurs
14、ive function index_of_smallest endl endl;int sample_array 10,number_used;fill_array(sample_array,10 z number_used);int i=index_of_smallest(sample_array,0,number_used);cout The number of elements is number_used endl;cout For the minimum element in the array INDEX=i endl;cout The array element is endl
15、 endl;sample_arrayicout The elements in the array are:n;for(int index=0;index number_used;index+)cout sample_arrayindex cout endl;return 0;)/Uses iostreamvoid fill_array(int a,int size,int&number_used)using namespace std;cout nEnter up to”size nonnegative whole numbers.nn Mark the end of the list wi
16、th”n e x t;w hile(next=0)&(index n e x t;)num ber_used=in d e x;)Recursive Function I ndex_o f _Sma 11 e s tThis recursive function returns the index of the minimum element in the array segment betweens ta rt_ in d e x and num ber_used.Non recursive Case:If we have only one element in a subarray whe
17、re s ta rt_ in d e x has thevalue num ber_used then that element is the minimum,and s ta rt_ in d e x is the index wewant.Recursive Case:If there is more than one element,take the element with smallest index andcompare its value to the minimum value of the array element at index returned by the func
18、tionoperating on the rest of the array.in t in d e x _ o f_ sm a lle st(c o n st in t a ;in t s ta r t_ in d e xz in tnum ber_used)-i f (start_index=num bereused-1)re tu rn start_index;in t min=a s ta rt_ in d e x;in t index_of_m in=in d e x _ o f_ sm a lle st(a,s ta r t_ in d e x+l,num ber_used);if
19、(m in a index_of_m in)re tu rn index_of_m in;e ls ereturn start_index;)A typical run:This program tests recursive function index_of_smallestEnter up to 10 nonnegative whole numbers.Mark the end of the list with a negative number.4 3 5 6 0 3-1The number of elements is 6For the minimum element in the
20、array INDEX=4The array element is 0The elements in the array are:4 3 5 6 0 3Another test run:This program tests recursive function index_of_smallestEnter up to 10 nonnegative whole numbers.Mark the end of the list with a negative number.9 2 3 8 4 5 6 3 2 9-1The number of elements is 10For the minimu
21、m element in the array INDEX=1The array element is 2The elements in the array are:9 2 3 8 4 5 6 3 2 93.No Solution Provided.4.Binomial Coefficients.Write a recursive function that uses the given recursive formula to calculate binomialcoefficients.Test.A second part gives a conventional formula for t
22、he factorial,instructs the student todiscover a recursive versions and to write a recursive function for the factorial.Test.Notes only on this problem.The students should have seen the Pascal Triangle inmathematics courses by this time.If not,suggest it to them.I do it this way:(x+y)1=l*x+l*y(x+y)2=
23、l*x2+2*x*y+2*y2(x+y)3=l*x3+3*x2*y1+3*x1*y2+y3(x+y)4=l*x4+4*x3*yr+6*x2*y2+4*x1*yi+y4(x+y)5=l*x5+5*x4*yL+10*x3*y2+10*x2*y3+5*x1*y4+x5Where the coefficients are1i1 31 41 5 10123610114 15 1The coefficients,when rearranged are:1 11 21 31 41 513 16 4 110 10 51Then we identify the rows with C(n,r)where the
24、 n is the second entry in any row,andr is the column of that row,starting with 0:C(l,0)C(l,l)C(2,0)C(2Z1)C(2,2)C(3z0)C(3Z1)C(3,2)C(3,3)C(4,0)C(4,l)C(4,2)C(4,3)C(4,4)C(5,0)C(5,1)C(5,2)C(5Z 3)C(5,4)C(5Z 5)Prod the students a little.They will see that adding any two row items gives the valuedirectly un
25、der the second item.There is the recursion relation they need:C(nz r)+C(nz r+1)=C(n+1,r+1)This is another umbrella recursion,similar in this respect to Programming problem#1.Ittakes considerable time and space to do this with recursion.If binomial coefficients are really needed,a bunch of them are l
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+ 大学 教程 课后 习题 答案 13
限制150内