Saturday, August 25, 2012

Given n find all possible representations of n in Fibonacci binary number system.

Consider the Fibonacci Seies 1, 2, 3, 5, 8, 13.....
Now consider a Fibonacci binary number system of numbers where numbers are considered as sum of Fibonacci numbers
Ex. 10 can be written as 8+2=>10010 and 17 can be written as 13+3+1 => 100101. This representation is similar to binary representation. Instead of powers of 2, Fibonacci numbers are used.
The question was, given n find all possible representations of n in Fibonacci binary number system.
as 10=8+2=>10010
also 10=5+3+2=>1110 

#include <stdio.h>
#include <string.h>
 
void printSol(int* sol, int size)
{
        int i;
 
        for( i = 0; i <= size; ++i )
                printf("%d",sol[i]);
        printf("\n");
}
 
void binaryFiboUtil(int* sol, int depth, int num,int* arr, int size)
{
        if(depth < 0 || num == 0){
                if(num == 0)
                   printSol(sol,size);
               return ;
        }
        else
        {
                if(arr[depth] <= num)
                {
                        sol[depth] = 1;
                        binaryFiboUtil(sol,depth-1,num-arr[depth],arr,size);
                        //sol[depth] = 0;
                }
                else
                {
                  sol[depth]=0;
                  binaryFiboUtil(sol,depth-1,num,arr,size);
                }
        }
}
 
void binaryFibo(int num)
{
        if(num <= 0 )
                return;
 
        int a, b, c, arr[100], top = -1;
 
        a = 0;
        b = 1;
        c = a+b;
 
        while( c <= num )
        {
                arr[++top] = c;
                a = b;
                b = c;
                c = a+b;
        }
        int sol[top+1];
 
        memset(sol,0,sizeof(sol));
        binaryFiboUtil(sol,top,num,arr,top);
}
 
int main()
{
        int num;
 
        scanf("%d", &num);
 
        binaryFibo(num);
 
        return 0;
} 
 
Thanks to a reader named "coder" for posting the code.
 

No comments :