Monday, 29 September 2014

Program to determine if given number is fibonacci or not..fully functional

C program to determine if the number is fibonacci number or not?

/*first let me tell you , a fibonacci number is a number of the form

*fibonacci(n)=fibonacci(n-1)+fibonacci(n-2);
*i.e. nth fibonacci number is sum of n-1 and (n-2)th fibonacci number given that
*fibonacci(0)=0 ,and
*fibonacci(1)=1;

*following is the program to help u with*/

#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
uint64_t fib(uint64_t);//u can take long long int
int check_fib(uint64_t);
uint64_t fibon[10000000];//array to store fibonacci number calculated

int main(){
uint64_t i;
long t,j;
uint64_t *a;
fibon[1]=1;
           //taking the number of test cases
       scanf("%ld",&t);
       //allocating that much element array
    a=calloc(t,sizeof(uint64_t));
       for(j=0;j<t;j++){
                        scanf("%llu",&a[j]);
       }
       for(j=0;j<t;j++){
    i=a[j];
       check_fib(i);
       printf("\n");
       }
       return 0 ;
       }

uint64_t fib(uint64_t n){
uint64_t l;
    if(n==0||n==1)
    return n;

   
    else if(fibon[n]){
return fibon[n];
}
else{

    l=fib(n-1)+fib(n-2);
    fibon[n]=l;
return fibon[n];
}
return;
}

int check_fib(uint64_t i){
     uint64_t j,l;
     j=2;
    if(i<10000000){
     if(i==fib(0)||i==fib(1)){
                              printf("IsFibo");
                              return 0;
                              }
     else {
          while(j<=i+1&&i!=fib(j))
                      j++;
                     
          if(j<=i+1)
    printf("IsFibo");
    else
          printf("IsNotFibo");
          }
}
else{
while(fib(j)<i)
j++;
if(fib(j)==i)
printf("IsFibo");
else
printf("IsNotFibo");
}
          return 0;
     }                   



/* An easy way to determine if the given number is fibonacci or not
 if the number is n
calculate (5n*n+4) or (5n*n-4) is a perfect square or not. if it is than its a fibonacci number.
Try it yourself
Thank You!!
*/

No comments:

Post a Comment