This blog is under construction

Sunday 23 June 2013

C program to check whether the given number is fibonacci or not

What is Fibonacci Number?
Fibonacci numbers are the numbers in the following sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..
0 and 1 are the first two Fibonacci numbers in the sequence and the subsequent numbers are the sum of previous two.

Write a C program to check whether the given number is Fibonacci or not.


  #include <stdio.h>
  int main() {
        int data, num1 = 0, num2 = 1, temp, flag = 0;

        /* get the input from the user */
        printf("Enter ur input:");
        scanf("%d", &data);

        /* 0 and 1 are fibonacci numbers */
        if (data == num1 || data == num2) {
                printf("%d is a fibonacci number\n", data);
                return 0;
        }

        /* checking whether a given number is fobonacci no or not */
        while (num2 <= data) {
                temp = num2;
                num2 = num1 + num2;
                num1 = temp;
                if (num2 == data) {
                        flag = 1;
                        break;
                }
        }

        /* print the results */
        if (flag) {
                printf("%d is a fibonacci number\n", data);
        } else {
                printf("%d is not a fibonacci number\n", data);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter ur input:35
  35 is not a fibonacci number



1 comment:

  1. What if a number is a large as 10^5. It will consume a lot of memory.

    ReplyDelete