Program to print the nth term of the Fibonacci series.
More...
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
|
unsigned int | fib (int number) |
| for assert() for errno - to determine whether there is an error while using strtol()
|
|
int | getInput (void) |
| Get the input from the user.
|
|
static void | test () |
| self-test implementation
|
|
int | main () |
| Main function.
|
|
Program to print the nth term of the Fibonacci series.
Fibonacci series generally starts from 0 and 1. Every next term in the series is equal to the sum of the two preceding terms. For further info: https://en.wikipedia.org/wiki/Fibonacci_sequence
- Author
- Luiz Carlos Aguiar C
-
Niranjan
◆ fib()
unsigned int fib |
( |
int |
number | ) |
|
for assert() for errno - to determine whether there is an error while using strtol()
for input, output for exit() - to exit the program to calculate time taken by fib()
Determines the nth Fibonacci term
- Parameters
-
number | - n in "nth term" and it can't be negative as well as zero |
- Returns
- nth term in unsigned type
- Warning
- Only till 47th and 48th fibonacci element can be stored in
int
and unsigned int
respectively (takes more than 20 seconds to print)
27{
28
29 if (number <= 0)
30 {
31 fprintf(stderr, "Illegal Argument Is Passed!\n");
32 exit(EXIT_FAILURE);
33 }
34
35
36 if (number == 1)
37 return 0;
38
39 if (number == 2)
40 return 1;
41
42
43 return fib(number - 1) +
fib(number - 2);
44}
unsigned int fib(int number)
for assert() for errno - to determine whether there is an error while using strtol()
Definition fibonacci.c:26
◆ getInput()
Get the input from the user.
- Returns
- valid argument to the fibonacci function
51{
52 int num, excess_len;
54
55 while (1)
56 {
57 printf("Please enter a valid number:");
59
60 excess_len = 0;
64 while (getchar() != '\n') excess_len++;
65 }
66
67 num = strtol(
buffer, &endPtr,
68 10);
69
70
71 if (
72 (excess_len > 0 || num > 48) ||
73
74 (*endPtr != '\0' && *endPtr != '\n') ||
75
77 {
78 continue;
79 }
80
81 break;
82 }
83
84 printf("\nEntered digit: %d (it might take sometime)\n", num);
85 return num;
86}
struct used to store character in certain times
Definition min_printf.h:35
◆ main()
Main function.
- Returns
- 0 on exit
104{
105
107 printf("Tests passed...\n");
108
109
110 printf(
111 "Enter n to find nth fibonacci element...\n"
112 "Note: You would be asked to enter input until valid number ( less "
113 "than or equal to 48 ) is entered.\n");
114
116 clock_t start, end;
117
118 start = clock();
119 printf(
"Fibonacci element %d is %u ", number,
fib(number));
120 end = clock();
121
122 printf("in %.3f seconds.\n", ((double)(end - start)) / CLOCKS_PER_SEC );
123 return 0;
124}
static void test()
self-test implementation
Definition fibonacci.c:92
int getInput(void)
Get the input from the user.
Definition fibonacci.c:50
◆ test()
static void test |
( |
void |
| ) |
|
|
static |
self-test implementation
- Returns
- void