Fibonacci coding encodes an integer into binary number using Fibonacci Representation of the number. The idea is based on Zeckendorf’s Theorem which states that every positive integer can be written uniquely as a sum of distinct non-neighboring Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..).
The Fibonacci code word for a particular integer is exactly the integer's Zeckendorf representation with the order of its digits reversed and an additional "1" appended to the end. The extra 1 is appended to indicate the end of code (Note that the code never contains two consecutive 1s as per Zeckendorf’s Theorem. The representation uses Fibonacci numbers starting from 1 (2'nd Fibonacci Number). So the Fibonacci Numbers used are 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, …….
Given a number n, print its Fibonacci code.
Examples:
Input: n = 1
Output: 11
1 is first Fibonacci number in this representation
and an extra 1 is appended at the end.
Input: n = 11
Output: 001011
11 is sum of 8 and 3. The last 1 represents extra 1
that is always added. A 1 before it represents 8. The
third 1 (from beginning) represents 3.
We strongly recommend you to minimize your browser and try this yourself first.
The following algorithm takes an integer as input and generates a string that stores Fibonacci Encoding.
Find the largest Fibonacci number f less than or equal to n. Say it is the i'th number in the Fibonacci series. The length of codeword for n will be i+3 characters (One for extra 1 appended at the end, One because i is an index, and one for '\0'). Assuming that the Fibonacci series is stored:
- Let f be the largest Fibonacci less than or equal to n, prepend ‘1’ in the binary string. This indicates usage of f in representation for n. Subtract f from n: n = n - f
- Else if f is greater than n, prepend ‘0’ to the binary string.
- Move to the Fibonacci number just smaller than f .
- Repeat until zero remainder (n = 0)
- Append an additional ‘1’ to the binary string. We obtain an encoding such that two consecutive 1s indicate the end of a number (and the start of the next).
Below is the implementation of above algorithm.
C++
/* C++ program for Fibonacci Encoding of a positive integer n */
#include <bits/stdc++.h>
using namespace std;
// To limit on the largest Fibonacci number to be used
#define N 30
/* Array to store fibonacci numbers. fib[i] is going
to store (i+2)'th Fibonacci number*/
int fib[N];
// Stores values in fib and returns index of the largest
// fibonacci number smaller than n.
int largestFiboLessOrEqual(int n)
{
fib[0] = 1; // Fib[0] stores 2nd Fibonacci No.
fib[1] = 2; // Fib[1] stores 3rd Fibonacci No.
// Keep Generating remaining numbers while previously
// generated number is smaller
int i;
for (i=2; fib[i-1]<=n; i++)
fib[i] = fib[i-1] + fib[i-2];
// 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.
return (i-2);
}
/* Returns pointer to the char string which corresponds to
code for n */
char* fibonacciEncoding(int n)
{
int index = largestFiboLessOrEqual(n);
//allocate memory for codeword
char *codeword = (char*)malloc(sizeof(char)*(index+3));
// index of the largest Fibonacci f <= n
int i = index;
while (n)
{
// Mark usage of Fibonacci f (1 bit)
codeword[i] = '1';
// Subtract f from n
n = n - fib[i];
// Move to Fibonacci just smaller than f
i = i - 1;
// Mark all Fibonacci > n as not used (0 bit),
// progress backwards
while (i>=0 && fib[i]>n)
{
codeword[i] = '0';
i = i - 1;
}
}
//additional '1' bit
codeword[index+1] = '1';
codeword[index+2] = '\0';
//return pointer to codeword
return codeword;
}
/* driver function */
int main()
{
int n = 143;
cout <<"Fibonacci code word for " <<n <<" is " << fibonacciEncoding(n);
return 0;
}
// This code is contributed by shivanisinghss2110
C
/* C program for Fibonacci Encoding of a positive integer n */
#include<stdio.h>
#include<stdlib.h>
// To limit on the largest Fibonacci number to be used
#define N 30
/* Array to store fibonacci numbers. fib[i] is going
to store (i+2)'th Fibonacci number*/
int fib[N];
// Stores values in fib and returns index of the largest
// fibonacci number smaller than n.
int largestFiboLessOrEqual(int n)
{
fib[0] = 1; // Fib[0] stores 2nd Fibonacci No.
fib[1] = 2; // Fib[1] stores 3rd Fibonacci No.
// Keep Generating remaining numbers while previously
// generated number is smaller
int i;
for (i=2; fib[i-1]<=n; i++)
fib[i] = fib[i-1] + fib[i-2];
// 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.
return (i-2);
}
/* Returns pointer to the char string which corresponds to
code for n */
char* fibonacciEncoding(int n)
{
int index = largestFiboLessOrEqual(n);
//allocate memory for codeword
char *codeword = (char*)malloc(sizeof(char)*(index+3));
// index of the largest Fibonacci f <= n
int i = index;
while (n)
{
// Mark usage of Fibonacci f (1 bit)
codeword[i] = '1';
// Subtract f from n
n = n - fib[i];
// Move to Fibonacci just smaller than f
i = i - 1;
// Mark all Fibonacci > n as not used (0 bit),
// progress backwards
while (i>=0 && fib[i]>n)
{
codeword[i] = '0';
i = i - 1;
}
}
//additional '1' bit
codeword[index+1] = '1';
codeword[index+2] = '\0';
//return pointer to codeword
return codeword;
}
/* driver function */
int main()
{
int n = 143;
printf("Fibonacci code word for %d is %s\n", n, fibonacciEncoding(n));
return 0;
}
Java
// Java program for Fibonacci Encoding
// of a positive integer n
import java.io.*;
class GFG{
// To limit on the largest Fibonacci
// number to be used
public static int N = 30;
// Array to store fibonacci numbers.
// fib[i] is going to store (i+2)'th
// Fibonacci number
public static int[] fib = new int[N];
// Stores values in fib and returns index of
// the largest fibonacci number smaller than n.
public static int largestFiboLessOrEqual(int n)
{
// Fib[0] stores 2nd Fibonacci No.
fib[0] = 1;
// Fib[1] stores 3rd Fibonacci No.
fib[1] = 2;
// Keep Generating remaining numbers while
// previously generated number is smaller
int i;
for(i = 2; fib[i - 1] <= n; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
// 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.
return(i - 2);
}
// Returns pointer to the char string which
// corresponds to code for n
public static String fibonacciEncoding(int n)
{
int index = largestFiboLessOrEqual(n);
// Allocate memory for codeword
char[] codeword = new char[index + 3];
// Index of the largest Fibonacci f <= n
int i = index;
while (n > 0)
{
// Mark usage of Fibonacci f(1 bit)
codeword[i] = '1';
// Subtract f from n
n = n - fib[i];
// Move to Fibonacci just smaller than f
i = i - 1;
// Mark all Fibonacci > n as not used
// (0 bit), progress backwards
while (i >= 0 && fib[i] > n)
{
codeword[i] = '0';
i = i - 1;
}
}
// Additional '1' bit
codeword[index + 1] = '1';
codeword[index + 2] = '\0';
String string = new String(codeword);
// Return pointer to codeword
return string;
}
// Driver code
public static void main(String[] args)
{
int n = 143;
System.out.println("Fibonacci code word for " +
n + " is " + fibonacciEncoding(n));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 program for Fibonacci Encoding
# of a positive integer n
# To limit on the largest
# Fibonacci number to be used
N = 30
# Array to store fibonacci numbers.
# fib[i] is going to store
# (i+2)'th Fibonacci number
fib = [0 for i in range(N)]
# Stores values in fib and returns index of
# the largest fibonacci number smaller than n.
def largestFiboLessOrEqual(n):
fib[0] = 1 # Fib[0] stores 2nd Fibonacci No.
fib[1] = 2 # Fib[1] stores 3rd Fibonacci No.
# Keep Generating remaining numbers while
# previously generated number is smaller
i = 2
while fib[i - 1] <= n:
fib[i] = fib[i - 1] + fib[i - 2]
i += 1
# 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.
return (i - 2)
# Returns pointer to the char string which
# corresponds to code for n
def fibonacciEncoding(n):
index = largestFiboLessOrEqual(n)
# allocate memory for codeword
codeword = ['a' for i in range(index + 2)]
# index of the largest Fibonacci f <= n
i = index
while (n):
# Mark usage of Fibonacci f (1 bit)
codeword[i] = '1'
# Subtract f from n
n = n - fib[i]
# Move to Fibonacci just smaller than f
i = i - 1
# Mark all Fibonacci > n as not used (0 bit),
# progress backwards
while (i >= 0 and fib[i] > n):
codeword[i] = '0'
i = i - 1
# additional '1' bit
codeword[index + 1] = '1'
# return pointer to codeword
return "".join(codeword)
# Driver Code
n = 143
print("Fibonacci code word for", n,
"is", fibonacciEncoding(n))
# This code is contributed by Mohit Kumar
C#
// C# program for Fibonacci Encoding
// of a positive integer n
using System;
class GFG{
// To limit on the largest Fibonacci
// number to be used
public static int N = 30;
// Array to store fibonacci numbers.
// fib[i] is going to store (i+2)'th
// Fibonacci number
public static int[] fib = new int[N];
// Stores values in fib and returns index of
// the largest fibonacci number smaller than n.
public static int largestFiboLessOrEqual(int n)
{
// Fib[0] stores 2nd Fibonacci No.
fib[0] = 1;
// Fib[1] stores 3rd Fibonacci No.
fib[1] = 2;
// Keep Generating remaining numbers while
// previously generated number is smaller
int i;
for(i = 2; fib[i - 1] <= n; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
// 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.
return(i - 2);
}
// Returns pointer to the char string which
// corresponds to code for n
public static String fibonacciEncoding(int n)
{
int index = largestFiboLessOrEqual(n);
// Allocate memory for codeword
char[] codeword = new char[index + 3];
// Index of the largest Fibonacci f <= n
int i = index;
while (n > 0)
{
// Mark usage of Fibonacci f(1 bit)
codeword[i] = '1';
// Subtract f from n
n = n - fib[i];
// Move to Fibonacci just smaller than f
i = i - 1;
// Mark all Fibonacci > n as not used
// (0 bit), progress backwards
while (i >= 0 && fib[i] > n)
{
codeword[i] = '0';
i = i - 1;
}
}
// Additional '1' bit
codeword[index + 1] = '1';
codeword[index + 2] = '\0';
string str = new string(codeword);
// Return pointer to codeword
return str;
}
// Driver code
static public void Main()
{
int n = 143;
Console.WriteLine("Fibonacci code word for " +
n + " is " + fibonacciEncoding(n));
}
}
// This code is contributed by rag2127
JavaScript
<script>
// Javascript program for Fibonacci Encoding
// of a positive integer n
// To limit on the largest Fibonacci
// number to be used
let N = 30;
// Array to store fibonacci numbers.
// fib[i] is going to store (i+2)'th
// Fibonacci number
let fib = new Array(N);
// Stores values in fib and returns index of
// the largest fibonacci number smaller than n.
function largestFiboLessOrEqual(n)
{
// Fib[0] stores 2nd Fibonacci No.
fib[0] = 1;
// Fib[1] stores 3rd Fibonacci No.
fib[1] = 2;
// Keep Generating remaining numbers while
// previously generated number is smaller
let i;
for(i = 2; fib[i - 1] <= n; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
// 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.
return(i - 2);
}
// Returns pointer to the char string which
// corresponds to code for n
function fibonacciEncoding(n)
{
let index = largestFiboLessOrEqual(n);
// Allocate memory for codeword
let codeword = new Array(index + 3);
// Index of the largest Fibonacci f <= n
let i = index;
while (n > 0)
{
// Mark usage of Fibonacci f(1 bit)
codeword[i] = '1';
// Subtract f from n
n = n - fib[i];
// Move to Fibonacci just smaller than f
i = i - 1;
// Mark all Fibonacci > n as not used
// (0 bit), progress backwards
while (i >= 0 && fib[i] > n)
{
codeword[i] = '0';
i = i - 1;
}
}
// Additional '1' bit
codeword[index + 1] = '1';
codeword[index + 2] = '\0';
let string =(codeword).join("");
// Return pointer to codeword
return string;
}
// Driver code
let n = 143;
document.write("Fibonacci code word for " +
n + " is " + fibonacciEncoding(n));
// This code is contributed by unknown2108
</script>
Output:
Fibonacci code word for 143 is 01010101011
Time complexity :- O(N)
Space complexity :- O(N+K)
Illustration

Field of application:
Data Processing & Compression - representing the data (which can be text, image, video...) in such a way that the space needed to store or transmit data is less than the size of input data. Statistical methods use variable-length codes, with the shorter codes assigned to symbols or group of symbols that have a higher probability of occurrence. If the codes are to be used over a noisy communication channel, their resilience to bit insertions, deletions and to bit-flips is of high importance.
Read more about the application here.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem