Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
fibonacci_fast.c File Reference

Compute \(m^{mth}\) Fibonacci number using the formulae: More...

#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
Include dependency graph for fibonacci_fast.c:

Functions

void fib (unsigned long n, unsigned long *C, unsigned long *D)
 
int main (int argc, char *argv[])
 

Detailed Description

Compute \(m^{mth}\) Fibonacci number using the formulae:

Author
Krishna Vedala
Date
2 October, 2019

\begin{eqnarray*} F_{2n-1} &=& F_n^2 + F_{n-1}^2 \\ F_{2n} &=& F_n\left(2F_{n-1} + F_n\right) \end{eqnarray*}

Function Documentation

◆ fib()

void fib ( unsigned long  n,
unsigned long *  C,
unsigned long *  D 
)

Returns the \(n^{th}\) and \(n+1^{th}\) Fibonacci number. The return variables are C & D respectively.

21 {
22  // Out of Range checking
23  if (n < 0)
24  {
25  printf("\nNo Such term !\n");
26  exit(0);
27  }
28 
29  unsigned long a, b, c, d;
30 
31  if (n == 0)
32  {
33  C[0] = 0;
34  if (D)
35  D[0] = 1;
36  return;
37  }
38 
39  fib(n >> 1, &c, &d); /* Compute F(n/2) */
40 
41  a = c * ((d << 1) - c);
42  b = c * c + d * d;
43  if (n % 2 == 0) /* If n is even */
44  {
45  C[0] = a;
46  if (D)
47  D[0] = b;
48  return;
49  }
50 
51  /**< If n is odd */
52  C[0] = b;
53  if (D)
54  D[0] = a + b;
55  return;
56 }

◆ main()

int main ( int  argc,
char *  argv[] 
)

main function

62 {
63  unsigned long number, result;
64 
65  setlocale(LC_NUMERIC, ""); // format the printf output
66 
67  // Asks for the number/position of term in Fibonnacci sequence
68  if (argc == 2)
69  number = atoi(argv[1]);
70  else
71  {
72  printf("Enter the value of n(n starts from 0 ): ");
73  scanf("%lu", &number);
74  }
75 
76  fib(number, &result, NULL);
77 
78  printf("The nth term is : %'lu \n", result);
79 
80  return 0;
81 }
Here is the call graph for this function:
fib
void fib(unsigned long n, unsigned long *C, unsigned long *D)
Definition: fibonacci_fast.c:20