Saturday, January 18, 2014

Miscellaneous

[Q.1] You are given an integer N, can you check if the number is an element of fibonacci series? The first few elements of fibonacci series are 
0,1,1,2,3,5,8,13….

Solution:

C++ Code:

#include<iostream>
using namespace std;

bool isFibo(int N)
{
    if(N==0 || N==1)
        return true;    
    int num = 1;
    int n1 = 1;
    int n2 = 0;    
    while(N > num)
    {
        num = n1 + n2;
        n2 = n1;
        n1 = num;        
    }
    if(num == N)
        return true;
    return false;
}

int main()
{
    int num = 0;
    cin >> num;
    
    if(isFibo(num))
        cout << "IsFibo" << endl;
    else
        cout << "IsNotFibo" << endl;
    getchar();
    return 0;
}
--------------------------------------------------

C# code:

using System;
using System.Collections.Generic;
using System.IO;

class Solution {
    static bool isFib(int N)
    {
        if(N==0 || N==1)
            return true;    
        int num = 1;
        int n1 = 1;
        int n2 = 0;
    
        while(N > num)
        {
            num = n1 + n2;
            n2 = n1;
            n1 = num;        
        }
        if(num == N)
            return true;
        return false;
    }

    static void Main(String[] args) {
        string sNum = Console.ReadLine();
        int num = int.Parse(sNum);
        
        if(isFib(num))
            Console.Write("IsFibo");
        else
            Console.Write("IsNotFibo");            
    }
}


No comments :

Post a Comment