Fibonacci Coding | To limit on the largest Fibonacci number to be used ; Array to store fibonacci numbers . fib [ i ] is going to store ( i + 2 ) 'th Fibonacci number ; Stores values in fib and returns index of the largest fibonacci number smaller than n . ; Fib [ 0 ] stores 2 nd Fibonacci No . ; Fib [ 1 ] stores 3 rd Fibonacci No . ; Keep Generating remaining numbers while previously generated number is smaller ; Return index of the largest fibonacci number smaller than or equal to n . Note that the above loop stopped when fib [ i - 1 ] became larger . ; Returns pointer to the char string which corresponds to code for n ; Allocate memory for codeword ; Index of the largest Fibonacci f <= n ; Mark usage of Fibonacci f ( 1 bit ) ; Subtract f from n ; Move to Fibonacci just smaller than f ; Mark all Fibonacci > n as not used ( 0 bit ) , progress backwards ; Additional '1' bit ; Return pointer to codeword ; Driver code
let N = 30 ; let fib = new Array ( N ) ; function largestFiboLessOrEqual ( n ) { fib [ 0 ] = 1 ; fib [ 1 ] = 2 ; let i ; for ( i = 2 ; fib [ i - 1 ] <= n ; i ++ ) { fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; } return ( i - 2 ) ; } function fibonacciEncoding ( n ) { let index = largestFiboLessOrEqual ( n ) ; let codeword = new Array ( index + 3 ) ; let i = index ; while ( n > 0 ) { codeword [ i ] = ' ' ; n = n - fib [ i ] ; i = i - 1 ; while ( i >= 0 && fib [ i ] > n ) { codeword [ i ] = ' ' ; i = i - 1 ; } } codeword [ index + 1 ] = ' ' ; codeword [ index + 2 ] = ' \0 ' ; let string = ( codeword ) . join ( " " ) ; return string ; } let n = 143 ; document . write ( " " + n + " " + fibonacciEncoding ( n ) ) ;