Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
fibonacci_formula.c File Reference

Finding Fibonacci number of any n number using [Binet's closed form formula](https://en.wikipedia.org/wiki/Fibonacci_number#Binet's_formula) compute \(f_{nth}\) Fibonacci number using the binet's formula: Fn = 1√5 * (1+√5 / 2)^n+1 − 1√5 * (1−√5 / 2)^n+1. More...

#include <math.h>
#include <stdio.h>
#include <assert.h>
Include dependency graph for fibonacci_formula.c:

Functions

int fib (unsigned int n)
 for pow and sqrt for printf for assert
 
static void test ()
 Self-test implementations.
 
int main ()
 Main function.
 

Detailed Description

Finding Fibonacci number of any n number using [Binet's closed form formula](https://en.wikipedia.org/wiki/Fibonacci_number#Binet's_formula) compute \(f_{nth}\) Fibonacci number using the binet's formula: Fn = 1√5 * (1+√5 / 2)^n+1 − 1√5 * (1−√5 / 2)^n+1.

Author
GrandSir

Function Documentation

◆ fib()

int fib ( unsigned int  n)

for pow and sqrt for printf for assert

Parameters
nindex of number in Fibonacci sequence
Returns
nth value of fibonacci sequence for all n >= 0
17 {
18 float seq = (1 / sqrt(5) * pow(((1 + sqrt(5)) / 2), n + 1)) - (1 / sqrt(5) * pow(((1 - sqrt(5)) / 2), n + 1));
19
20 // removing unnecessary fractional part by implicitly converting float to int
21 return seq;
22}

◆ main()

int main ( void  )

Main function.

Returns
0 on exit
52 {
53 test(); // run self-test implementations
54
55 for(int i = 0; i <= 10; i++){
56 printf("%d. fibonacci number is: %d\n", i, fib(i));
57 }
58 return 0;
59}
int fib(unsigned int n)
for pow and sqrt for printf for assert
Definition fibonacci_formula.c:17
static void test()
Self-test implementations.
Definition fibonacci_formula.c:28
Here is the call graph for this function:

◆ test()

static void test ( void  )
static

Self-test implementations.

Returns
void
28 {
29 /* this ensures that the first 10 number of fibonacci sequence
30 * (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
31 * matches with algorithm
32 */
33 assert(fib(0) == 1);
34 assert(fib(1) == 1);
35 assert(fib(2) == 2);
36 assert(fib(3) == 3);
37 assert(fib(4) == 5);
38 assert(fib(5) == 8);
39 assert(fib(6) == 13);
40 assert(fib(7) == 21);
41 assert(fib(8) == 34);
42 assert(fib(9) == 55);
43 assert(fib(10) == 89);
44
45 printf("All tests have successfully passed!\n");
46}
Here is the call graph for this function: