{"id":25725,"date":"2017-10-25T20:16:31","date_gmt":"2017-10-25T14:46:31","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25725"},"modified":"2017-10-25T20:16:31","modified_gmt":"2017-10-25T14:46:31","slug":"c-programming-fibonacci-numbers","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-fibonacci-numbers\/","title":{"rendered":"C Programming &#8211; Fibonacci numbers"},"content":{"rendered":"<p>The Fibonacci numbers are the numbers in the following integer sequence.<\/p>\n<p>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, \u2026\u2026..<\/p>\n<p>In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation<\/p>\n<p>Fn = Fn-1 + Fn-2<br \/>\nwith seed values<\/p>\n<p>F0 = 0 and F1 = 1.<\/p>\n<p>Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n &gt; 1, it should return Fn-1 + Fn-2<\/p>\n<p>For n = 9<br \/>\nOutput:34<br \/>\nFollowing are different methods to get the nth Fibonacci number.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Method 1 ( Use recursion )<br \/>\nA simple method that is a direct recursive implementation mathematical recurrence relation given above.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c program1<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/Fibonacci Series using Recursion<br\/>#include&lt;stdio.h&gt;<br\/>int fib(int n)<br\/>{<br\/>   if (n &lt;= 1)<br\/>      return n;<br\/>   return fib(n-1) + fib(n-2);<br\/>}<br\/> <br\/>int main ()<br\/>{<br\/>  int n = 9;<br\/>  printf(&quot;%d&quot;, fib(n));<br\/>  getchar();<br\/>  return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output<\/p>\n<pre>34<\/pre>\n<p><em>Time Complexity:<\/em> T(n) = T(n-1) + T(n-2) which is exponential.<\/p>\n<p>We can observe that this implementation does a lot of repeated work (see the following recursion tree). So this is a bad implementation for nth Fibonacci number.<\/p>\n<pre>                         fib(5)   \r\n                     \/             \\     \r\n               fib(4)                fib(3)   \r\n             \/      \\                \/     \\\r\n         fib(3)      fib(2)         fib(2)    fib(1)\r\n        \/     \\        \/    \\       \/    \\  \r\n  fib(2)   fib(1)  fib(1) fib(0) fib(1) fib(0)\r\n  \/    \\\r\nfib(1) fib(0)<\/pre>\n<p><em>Extra Space:<\/em> O(n) if we consider the function call stack size, otherwise O(1).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 2 ( Use Dynamic Programming )<\/strong><br \/>\nWe can avoid the repeated work done is the method 1 by storing the Fibonacci numbers calculated so far.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c program2<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/Fibonacci Series using Dynamic Programming<br\/>#include&lt;stdio.h&gt;<br\/> <br\/>int fib(int n)<br\/>{<br\/>  \/* Declare an array to store Fibonacci numbers. *\/<br\/>  int f[n+1];<br\/>  int i;<br\/> <br\/>  \/* 0th and 1st number of the series are 0 and 1*\/<br\/>  f[0] = 0;<br\/>  f[1] = 1;<br\/> <br\/>  for (i = 2; i &lt;= n; i++)<br\/>  {<br\/>      \/* Add the previous 2 numbers in the series<br\/>         and store it *\/<br\/>      f[i] = f[i-1] + f[i-2];<br\/>  }<br\/> <br\/>  return f[n];<br\/>}<br\/> <br\/>int main ()<br\/>{<br\/>  int n = 9;<br\/>  printf(&quot;%d&quot;, fib(n));<br\/>  getchar();<br\/>  return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>34<\/pre>\n<p><em>Time Complexity:<\/em> O(n)<br \/>\n<em>Extra Space: <\/em>O(n)<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 3 ( Space Optimized Method 2 )<\/strong><br \/>\nWe can optimize the space used in method 2 by storing the previous two numbers only because that is all we need to get the next Fibonacci number in series.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c program3<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ Fibonacci Series using Space Optimized Method<br\/>#include&lt;stdio.h&gt;<br\/>int fib(int n)<br\/>{<br\/>  int a = 0, b = 1, c, i;<br\/>  if( n == 0)<br\/>    return a;<br\/>  for (i = 2; i &lt;= n; i++)<br\/>  {<br\/>     c = a + b;<br\/>     a = b;<br\/>     b = c;<br\/>  }<br\/>  return b;<br\/>}<br\/> <br\/>int main ()<br\/>{<br\/>  int n = 9;<br\/>  printf(&quot;%d&quot;, fib(n));<br\/>  getchar();<br\/>  return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: O(n)<br \/>\nExtra Space: O(1)<\/p>\n[ad type=&#8221;banner&#8221;]\n<strong>Method 4<\/strong> ( Using power of the matrix {{1,1},{1,0}} )<br \/>\nThis another O(n) which relies on the fact that if we n times multiply the matrix M = {{1,1},{1,0}} to itself (in other words calculate power(M, n )), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix.<\/p>\n<p>&nbsp;<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c program4<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include &lt;stdio.h&gt;<br\/> <br\/>\/* Helper function that multiplies 2 matrices F and M of size 2*2, and<br\/>  puts the multiplication result back to F[][] *\/<br\/>void multiply(int F[2][2], int M[2][2]);<br\/> <br\/>\/* Helper function that calculates F[][] raise to the power n and puts the<br\/>  result in F[][]<br\/>  Note that this function is designed only for fib() and won&#039;t work as general<br\/>  power function *\/<br\/>void power(int F[2][2], int n);<br\/> <br\/>int fib(int n)<br\/>{<br\/>  int F[2][2] = {{1,1},{1,0}};<br\/>  if (n == 0)<br\/>      return 0;<br\/>  power(F, n-1);<br\/> <br\/>  return F[0][0];<br\/>}<br\/> <br\/>void multiply(int F[2][2], int M[2][2])<br\/>{<br\/>  int x =  F[0][0]*M[0][0] + F[0][1]*M[1][0];<br\/>  int y =  F[0][0]*M[0][1] + F[0][1]*M[1][1];<br\/>  int z =  F[1][0]*M[0][0] + F[1][1]*M[1][0];<br\/>  int w =  F[1][0]*M[0][1] + F[1][1]*M[1][1];<br\/> <br\/>  F[0][0] = x;<br\/>  F[0][1] = y;<br\/>  F[1][0] = z;<br\/>  F[1][1] = w;<br\/>}<br\/> <br\/>void power(int F[2][2], int n)<br\/>{<br\/>  int i;<br\/>  int M[2][2] = {{1,1},{1,0}};<br\/> <br\/>  \/\/ n - 1 times multiply the matrix to {{1,0},{0,1}}<br\/>  for (i = 2; i &lt;= n; i++)<br\/>      multiply(F, M);<br\/>}<br\/> <br\/>\/* Driver program to test above function *\/<br\/>int main()<br\/>{<br\/>  int n = 9;<br\/>  printf(&quot;%d&quot;, fib(n));<br\/>  getchar();<br\/>  return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: O(n)<br \/>\nExtra Space: O(1)<br \/>\nMethod 5 ( Optimized Method 4 )<br \/>\nThe method 4 can be optimized to work in O(Logn) time complexity. We can do recursive multiplication to get power(M, n) in the prevous method (Similar to the optimization done in this post)<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C program5<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include &lt;stdio.h&gt;<br\/> <br\/>void multiply(int F[2][2], int M[2][2]);<br\/> <br\/>void power(int F[2][2], int n);<br\/> <br\/>\/* function that returns nth Fibonacci number *\/<br\/>int fib(int n)<br\/>{<br\/>  int F[2][2] = {{1,1},{1,0}};<br\/>  if (n == 0)<br\/>    return 0;<br\/>  power(F, n-1);<br\/>  return F[0][0];<br\/>}<br\/> <br\/>\/* Optimized version of power() in method 4 *\/<br\/>void power(int F[2][2], int n)<br\/>{<br\/>  if( n == 0 || n == 1)<br\/>      return;<br\/>  int M[2][2] = {{1,1},{1,0}};<br\/> <br\/>  power(F, n\/2);<br\/>  multiply(F, F);<br\/> <br\/>  if (n%2 != 0)<br\/>     multiply(F, M);<br\/>}<br\/> <br\/>void multiply(int F[2][2], int M[2][2])<br\/>{<br\/>  int x =  F[0][0]*M[0][0] + F[0][1]*M[1][0];<br\/>  int y =  F[0][0]*M[0][1] + F[0][1]*M[1][1];<br\/>  int z =  F[1][0]*M[0][0] + F[1][1]*M[1][0];<br\/>  int w =  F[1][0]*M[0][1] + F[1][1]*M[1][1];<br\/> <br\/>  F[0][0] = x;<br\/>  F[0][1] = y;<br\/>  F[1][0] = z;<br\/>  F[1][1] = w;<br\/>}<br\/> <br\/>\/* Driver program to test above function *\/<br\/>int main()<br\/>{<br\/>  int n = 9;<br\/>  printf(&quot;%d&quot;, fib(9));<br\/>  getchar();<br\/>  return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong><em>Time Complexity: <\/em>O(Logn)<\/strong><br \/>\n<em>Extra Space:<\/em> O(Logn) if we consider the function call stack size, otherwise O(1).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 6 (O(Log n) Time)<\/strong><br \/>\nBelow is one more interesting recurrence formula that can be used to find n\u2019th Fibonacci Number in O(Log n) time.<\/p>\n<pre>If n is even then k = n\/2:\r\nF(n) = [2*F(k-1) + F(k)]*F(k)\r\n\r\nIf n is odd then k = (n + 1)\/2\r\nF(n) = F(k)*F(k) + F(k-1)*F(k-1)<\/pre>\n<p>How does this formula work?<br \/>\nThe formula can be derived from above matrix equation.<br \/>\nfibonaccimatrix<\/p>\n<p>Taking determinant on both sides, we get<br \/>\n(-1)n = Fn+1Fn-1 \u2013 Fn2<br \/>\nMoreover, since AnAm = An+m for any square matrix A, the following identities can be derived (they are obtained form two different coefficients of the matrix product)<\/p>\n<p>FmFn + Fm-1Fn-1 = Fm+n-1<\/p>\n<p>By putting n = n+1,<\/p>\n<p>FmFn+1 + Fm-1Fn = Fm+n<\/p>\n<p>Putting m = n<\/p>\n<p>F2n-1 = Fn2 + Fn-12<\/p>\n<p>F2n = (Fn-1 + Fn+1)Fn = (2Fn-1 + Fn)Fn (Source: Wiki)<\/p>\n<p>To get the formula to be proved, we simply need to do following<br \/>\nIf n is even, we can put k = n\/2<br \/>\nIf n is odd, we can put k = (n+1)\/2<\/p>\n<p>Below is C++ implementation of above idea.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C Program 6<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C++ Program to find n&#039;th fibonacci Number in<br\/>\/\/ with O(Log n) arithmatic operations<br\/>#include &lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/> <br\/>const int MAX = 1000;<br\/> <br\/>\/\/ Create an array for memoization<br\/>int f[MAX] = {0};<br\/> <br\/>\/\/ Returns n&#039;th fuibonacci number using table f[]<br\/>int fib(int n)<br\/>{<br\/>    \/\/ Base cases<br\/>    if (n == 0)<br\/>        return 0;<br\/>    if (n == 1 || n == 2)<br\/>        return (f[n] = 1);<br\/> <br\/>    \/\/ If fib(n) is already computed<br\/>    if (f[n])<br\/>        return f[n];<br\/> <br\/>    int k = (n &amp; 1)? (n+1)\/2 : n\/2;<br\/> <br\/>    \/\/ Applyting above formula [Note value n&amp;1 is 1<br\/>    \/\/ if n is odd, else 0.<br\/>    f[n] = (n &amp; 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1))<br\/>           : (2*fib(k-1) + fib(k))*fib(k);<br\/> <br\/>    return f[n];<br\/>}<br\/> <br\/>\/* Driver program to test above function *\/<br\/>int main()<br\/>{<br\/>    int n = 9;<br\/>    printf(&quot;%d &quot;, fib(n));<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output :<\/p>\n<pre>34<\/pre>\n<p>Time complexity of this solution is O(Log n) as we divide the problem to half in every recursive call.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C Programming Fibonacci numbers &#8211; Mathematical algorithms &#8211; The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69866,1,83563,74058],"tags":[74939,71157,74988,75004,69955,74999,74996,75003,74995,71152,75007,74080,70077,72112,72113,70972,74997,75006,75002,74992,74998,75001,74989,75005,74950,74076,74975,74951,74938,74940,74072,74945,72439,74060,72468,74066,70848,74952,74941,74935,74987,74949,75000,74994,74991,74990,74290,74993,74934,74942],"class_list":["post-25725","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-fibonacci-numbers","category-mathematical-algorithms","tag-algorithm-of-fibonacci-series","tag-bubble-sort-c-program","tag-c-language-graphics","tag-c-language-online-test","tag-c-language-operator","tag-c-language-questions-and-answers","tag-c-language-structure","tag-c-language-syllabus","tag-c-language-theory","tag-c-program-for-bubble-sort","tag-c-program-for-factorial","tag-c-program-for-fibonacci-series","tag-c-program-for-linear-search","tag-c-program-for-palindrome","tag-c-program-for-prime-number","tag-c-program-for-selection-sort","tag-c-program-sample","tag-c-program-structure","tag-c-programming-pointers","tag-c-programming-question-bank","tag-c-programming-question-paper","tag-c-programming-quiz","tag-c-programming-series-examples","tag-download-c-language","tag-fibonacci","tag-fibonacci-c-program","tag-fibonacci-formula","tag-fibonacci-java","tag-fibonacci-number-program-in-java","tag-fibonacci-program","tag-fibonacci-program-in-c","tag-fibonacci-series","tag-fibonacci-series-algorithm","tag-fibonacci-series-c-program","tag-fibonacci-series-in-c-using-recursion-with-explanation","tag-for-loop-c-programming","tag-for-loop-in-c-programming","tag-how-to-calculate-fibonacci","tag-java-fibonacci","tag-java-program-fibonacci","tag-modular-programming-in-c","tag-number-series-program-in-c","tag-online-c-programming","tag-online-c-programming-test","tag-programs-on-recursion-in-c","tag-recursion-in-c-programming-example","tag-recursion-program-in-c","tag-structure-in-c-programming","tag-write-a-program-to-print-fibonacci-series","tag-write-ac-program-to-generate-fibonacci-series"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25725","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25725"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25725\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25725"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25725"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25725"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}