check number is fibonacci in csharp

To check if a number is a Fibonacci number, we need to determine if it can be written as the sum of two consecutive Fibonacci numbers. One way to do this is to iterate through the Fibonacci numbers until we reach a number greater than or equal to the input number. If the input number is the same as the current Fibonacci number, then it is a Fibonacci number. Here's how to do it in C#:

main.cs
public static bool IsFibonacci(int num)
{
    int a = 0;
    int b = 1;

    while (b <= num)
    {
        if (b == num)
        {
            return true;
        }

        int temp = a + b;
        a = b;
        b = temp;
    }

    return false;
}
254 chars
20 lines

In the above code, we start with the first two numbers of the Fibonacci sequence (0 and 1), and then iteratively compute the next number in the sequence by adding the previous two. We continue this process until we find a number greater than or equal to the input number. If the input number is equal to the current Fibonacci number, we return true. Otherwise, we return false.

related categories

gistlibby LogSnag