[Solved] Huge Fibonacci

$25

File Name: Huge_Fibonacci.zip
File Size: 131.88 KB

SKU: [Solved] Huge Fibonacci Category: Tag:
5/5 - (1 vote)

AbstractIn this programming assignment, you will implement a Fibonacci function that avoids repetitive computation by computing the sequence linearly from the bottom up: F(0) through F(n). You will also overcome the limitations of Cs 32-bit integers by storing very large integers in arrays of individual digits.By completing this assignment, you will gain experience crafting algorithms of moderate complexity, develop a deeper understanding of integer type limitations, become acquainted with unsigned integers, and reinforce your understanding of dynamic memory management in C. In the end, you will have a very fast and awesome program for computing huge Fibonacci numbers.

AttachmentsFibonacci.h, testcase{01-05}.c, output{01-05}.txt, and test-all.shDeliverablesFibonacci.c(Note! Capitalization of your filename matters!)

1. Overview1.1. Computational Considerations for Recursive Fibonacci Weve seen in class that calculating Fibonacci numbers with the most straightforward recursive implementation of the function is prohibitively slow, as there is a lot of repetitive

computation:

int fib(int n){// base cases: F(0) = 0, F(1) = 1if (n < 2)return n;// definition of Fibonacci: F(n) = F(n 1) + F(n 2)return fib(n 1) + fib(n 2);}

This recursive function sports an exponential runtime. We saw in class that we can achieve linear runtime by building from our base cases, F(0) = 0 and F(1) = 1, toward our desired result, F(n). We thus avoid our expensive and exponentially EXplOsIVe recursive function calls.The former approach is called top-down processing, because we work from n down toward our base cases. The latter approach is called bottom-up processing, because we build from our base cases up toward our desired result, F(n). In general, the process by which we eliminate repetitive recursive callsby re-ordering our computation is called dynamic programming, and is a topic we will explore in more depth in COP 3503 (Computer Science II).1.2. Representing Huge Integers in COur linear Fibonacci function has a big problem, though, which is perhaps less obvious than the original runtime issue: when computing the sequence, we quickly exceed the limits of Cs 32-bit integer representation. On most modern systems, the maximum int value in C is 232-1, or 2,147,483,647.1 The first Fibonacci number to exceed that limit is F(47) = 2,971,215,073.Even Cs 64-bit unsigned long long int type is only guaranteed to represent non-negative integers up to and including 18,446,744,073,709,551,615 (which is 264-

1).2 The Fibonacci number F(93) is 12,200,160,415,121,876,738, which can be stored as an unsigned long long int. However, F(94) is 19,740,274,219,868,223,167, which is too big to store in any of Cs extended integer data types.To overcome this limitation, we will represent integers in this program using arrays, where each index holds a single digit of an integer.3 For reasons that will soon become apparent, we will store our 1 To see the upper limit of the int data type on your system, #include <limits.h, then printf(%d
, INT_MAX);

2 To see the upper limit of the unsigned long long int data type on your system, #include <limits.h, then printf(%llu
, ULLONG_MAX);

3 Admittedly, there is a lot of wasted space with this approach. We only need 4 bits to represent all the digits in the range 0 through 9, yet the int type on most modern systems is 32 bits. Thus, were wasting 28 bits for every digit in the hugeintegers we want to represent! Even Cs smallest data type utilizes at least one byte (8 bits), giving us at least 4 bits of unnecessary overhead.integers in reverse order in these arrays. So, for example, the numbers2,147,483,648 and 10,0087would be represented as:a[]: 8 4 6 3 8 4 7 4 1 20 1 2 3 4 5 6 7 8 9b[]: 7 8 0 0 0 10 1 2 3 4 5Storing these integers in reverse order makes it really easy to add two of them together. The ones digits for both integers are stored at index [0] in their respective arrays, the tens digits are at index [1], the hundreds digits are at index [2], and so on. How convenient!So, to add these two numbers together, we add the values at index [0] (8 + 7 = 15), throw down the 5 at index [0] in some new array where we want to store the sum, carry the 1, add it to the values at index [1] in our arrays (1 + 4 + 8 = 13), and so on:a[]: 8 4 6 3 8 4 7 4 1 2+ + + + + + + + + +b[]: 7 8 0 0 0 1 0 0 0 0 sum[]: 5 3 7 3 8 5 7 4 1 20 1 2 3 4 5 6 7 8 9In this program, we will use this array representation for integers. The arrays will be allocated dynamically, and we will stuff each array inside a struct that also keeps track of the arrays length:typedef struct HugeInteger{// a dynamically allocated array to hold the digits// of a huge integer, stored in reverse orderint *digits;// the number of digits in the huge integer (which is// approximately equal to the length of the array)int length;} HugeInteger;1.3. Unsigned Integers and limits.hTheres one final curve ball you have to deal with: there are a few places where your program will utilize unsigned integers. This is no cause to panic. An unsigned integer is just an integer that cant be negative. (Theres no sign associated with the value. Its always positive.) You declare an unsignedinteger like so:unsigned int n;Because an unsigned int is typically 32 bits (like the normal int data type), but doesnt need to use any of those bits to signify a sign, it can eke out a higher maximum positive integer value than a normal int.For at least one function in this assignment, youll need to know what the maximum value is that you can represent using an unsigned int on the system where your program is running. That value is defined in your systems limits.h file, which you should #include from your Fibonacci.c source file, like so:#include <limits.hlimits.h defines a value called UINT_MAX, which is the maximum value an unsigned int can hold. Italso defines INT_MAX (the maximum value an int can hold), UINT_MIN, INT_MIN, and many others thatyou might want to read up on in your spare time.If you want to print an unsigned int, the correct conversion code is %u. For example:unsigned int n = UINT_MAX;printf(Max unsigned int value: %u
, n);Note that (UINT_MAX + 1) necessarily causes integer overflow, but since an unsigned int cant be negative, (UINT_MAX + 1) just wraps back around to zero. Try this out for fun:4unsigned int n = UINT_MAX;printf(Max unsigned int value (+1): %u
, n + 1);Compare this, for example, to the integer overflow caused by the following:int n = INT_MAX;printf(Max int value (+1): %d
, n + 1);4 Here, fun is a relative term.2. Attachments2.1. Header File (Fibonacci.h)This assignment includes a header file, Fibonacci.h, which contains the definition for the HugeInteger struct, as well as functional prototypes for all the required functions in this assignment.You should #include this header file from your Fibonacci.c source file, like so:#include Fibonacci.h2.2. Test CasesThis assignment comes with multiple sample main files (testcase{01-05}.c), which you can compile with your Fibonacci.c source file. For more information about compiling projects with multiple source files, see Section 4, Compilation and Testing (CodeBlocks), and Section 5, Compilation and Testing (Linux/Mac Command Line).2.3. Sample Output FilesAlso included are a number of sample output files that show the expected results of executing your program (output{01-05}.txt).2.4. DisclaimerThe test cases included with this assignment are by no means comprehensive. Please be sure to develop your own test cases, and spend some time thinking of edge cases that might break each of therequired functions. In creating your own test cases, you should always ask yourself, How could these functions be called in ways that dont violate the program specification, but which havent already been covered in the test cases included with the assignment?2.5. test-all.shWeve also included a script, test-all.sh, that will compile and run all test cases for you. You can run it on Eustis by placing it in a directory with Fibonacci.c, Fibonacci.h, and all the test case files, and typing:bash test-all.sh3. Function RequirementsIn the source file you submit, Fibonacci.c, you must implement the following functions. You may implement any auxiliary functions you need to make these work, as well. Notice that none of your functions should print anything to the screen.HugeInteger *hugeAdd(HugeInteger *p, HugeInteger *q);Description: Return a pointer to a new, dynamically allocated HugeInteger struct that contains the result of adding the huge integers represented by p and q.Special Notes: If a NULL pointer is passed to this function, simply return NULL. If any dynamic memory allocation functions fail within this function, also return NULL, but be careful to avoid memory leaks when you do so.Hint: Before adding two huge integers, you will want to create an array to store the result. You might find it helpful to make the array slightly larger than is absolutely necessary in some cases.As long as that extra overhead is bounded by a very small constant, thats okay. (In this case, the structs length field should reflect the number of meaningful digits in the array, not the actual length of the array, which will necessarily be a bit larger.)Returns: A pointer to the newly allocated HugeInteger struct, or NULL in the special cases mentioned above.HugeInteger *hugeDestroyer(HugeInteger *p);Description: Destroy any and all dynamically allocated memory associated with p. Avoid segmentation faults and memory leaks.Returns: NULLHugeInteger *parseString(char *str);Description: Convert a number from string format to HugeInteger format. (For example function calls, see testcase01.c.)Special Notes: If the empty string () is passed to this function, treat it as a zero (0). If any dynamic memory allocation functions fail within this function, or if str is NULL, return NULL, but be careful to avoid memory leaks when you do so. You may assume the string will only contain ASCII digits 0 through 9, and that there will be no leading zeros in the string.Returns: A pointer to the newly allocated HugeInteger struct, or NULL if dynamic memory allocation fails or if str is NULL.HugeInteger *parseInt(unsigned int n)Description: Convert the unsigned integer n to HugeInteger format.Special Notes: If any dynamic memory allocation functions fail within this function, returnNULL, but be careful to avoid memory leaks when you do so.Returns: A pointer to the newly allocated HugeInteger struct, or NULL if dynamic memoryallocation fails at any point.unsigned int *toUnsignedInt(HugeInteger *p);Description: Convert the integer represented by p to a dynamically allocated unsigned int,and return a pointer to that value. If p is NULL, simply return NULL. If the integer represented byp exceeds the maximum unsigned int value defined in limits.h, return NULL.Note: The sole reason this function returns a pointer instead of an unsigned int is so that wecan return NULL to signify failure in cases where p cannot be represented as an unsigned int.Returns: A pointer to the dynamically allocated unsigned integer, or NULL if the value cannotbe represented as an unsigned integer (including the case where p is NULL).HugeInteger *fib(int n);Description: This is your Fibonacci function; this is where the magic happens. Implement aniterative solution that runs in O(nk) time and returns a pointer to a HugeInteger struct thatcontains F(n). (See runtime note below.) Be sure to prevent memory leaks before returning fromthis function.Runtime Consideration: In the O(nk) runtime restriction, n is the parameter passed to thefunction, and k is the number of digits in F(n). So, within this function, you can make a total ofn calls to a function that is O(k) (or faster).Space Consideration: When computing F(n) for large n, its important to keep as fewFibonacci numbers in memory as necessary at any given time. For example, in building up toF(10000), you wont want to hold Fibonacci numbers F(0) through F(9999) in memory all atonce. Find a way to have only a few Fibonacci numbers in memory at any given time over thecourse of a single call to fib().Special Notes: You may assume that n is a non-negative integer. If any dynamic memoryallocation functions fail within this function, return NULL, but be careful to avoid memory leakswhen you do so.Returns: A pointer to a HugeInteger representing F(n), or NULL if dynamic memory allocationfails.double difficultyRating(void);Returns: A double indicating how difficult you found this assignment on a scale of 1.0(ridiculously easy) through 5.0 (insanely difficult).double hoursSpent(void);Returns: An estimate (greater than zero) of the number of hours you spent on this assignment.4. Compilation and Testing (CodeBlocks)The key to getting multiple files to compile into a single program in CodeBlocks (or any IDE) is tocreate a project. Here are the step-by-step instructions for creating a project in CodeBlocks, importingFibonacci.h, your Fibonacci.c file (even if its just an empty file so far), and any of the samplemain files included with this writeup.1. Start CodeBlocks.2. Create a New Project (File New Project).3. Choose Empty Project and click Go.4. In the Project Wizard that opens, click Next.5. Input a title for your project (e.g., Fibonacci).6. Choose a folder (e.g., Desktop) where CodeBlocks can create a subdirectory for the project.7. Click Finish.Now you need to import your files. You have two options:1. Drag your source and header files into CodeBlocks. Then right click the tab for each file andchoose Add file to active project. or 2. Go to Project Add Files. Browse to the directory with the source and header files you wantto import. Select the files from the list (using CTRL-click to select multiple files). ClickOpen. In the dialog box that pops up, click OK.You should now be good to go. Try to build and run the project (F9).Note! Even if you develop your code with CodeBlocks on Windows, you ultimately have to transfer itto the Eustis server to compile and test it there. See the following page (Section 5, Compilation andTesting (Linux/Mac Command Line)) for instructions on command line compilation in Linux.5. Compilation and Testing (Linux/Mac Command Line)To compile multiple source files (.c files) at the command line:gcc Fibonacci.c testcase01.cBy default, this will produce an executable file called a.out, which you can run by typing:./a.outIf you want to name the executable file something else, use:gcc Fibonacci.c testcase01.c -o fib.exeand then run the program using:./fib.exeRunning the program could potentially dump a lot of output to the screen. If you want to redirect youroutput to a text file in Linux, its easy. Just run the program using the following command, which willcreate a file called whatever.txt that contains the output from your program:./fib.exe whatever.txtLinux has a helpful command called diff for comparing the contents of two files, which is reallyhelpful here since weve provided several sample output files. You can see whether your outputmatches ours exactly by typing, e.g.:diff whatever.txt output01.txtIf the contents of whatever.txt and output01.txt are exactly the same, diff wont have any output.It will just look like this:[email protected]:~$ diff whatever.txt output01.txt[email protected]:~$ _If the files differ, it will spit out some information about the lines that arent the same. For example:[email protected]:~$ diff whatever.txt output01.txt6c6< F(5) = 3F(5) = 5[email protected]:~$ _6. DeliverablesSubmit a single source file, named Fibonacci.c, via Webcourses. The source file should containdefinitions for all the required functions (listed above), as well as any auxiliary functions you need tomake them work.Your source file must not contain a main() function. Do not submit additional source files, and do notsubmit a modified Fibonacci.h header file. Your program must compile and run on Eustis to receivecredit. Programs that do not compile will receive an automatic zero. Specifically, your program mustcompile without any special flags, as in:gcc Fibonacci.c testcase01.cBe sure to include your name and NID as a comment at the top of your source file.7. GradingThe expected scoring breakdown for this programming assignment is:75% Correct output for test cases used in grading15% Implementation details (manual inspection of your code)10% Comments and whitespaceYour grade will be based primarily on your programs ability to compile and produce the exact outputexpected. Even minor deviations (such as capitalization or punctuation errors) in your output will causeyour programs output to be marked as incorrect, resulting in severe point deductions. The same is trueof how you name your functions and their parameters. Please be sure to follow all requirementscarefully and test your program thoroughly.Additional points will be awarded for style (proper commenting and whitespace) and adherence toimplementation requirements. For example, the graders might inspect your hugeDestroyer() functionto see that it is actually freeing up memory properly, or your fib() function to see that it has nomemory leaks.Please note that you will not receive credit for test cases that call your Fibonacci function if thatfunctions runtime is worse than O(nk), or if your program has memory leaks that slow downexecution. In grading, programs that take longer than a fraction of a second per test case (or perhaps awhole second or two for very large test cases) will be terminated. That wont be enough time for atraditional recursive implementation of the Fibonacci function to compute results for the large values ofn that I will pass to your programs.Your Fibonacci.c must not include a main() function. If it does, your code will fail to compileduring testing, and you will receive zero credit for the assignment.Special Restrictions: As always, you must avoid the use of global variables, mid-function variabledeclarations, and system calls (such as system(pause)).

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[Solved] Huge Fibonacci
$25