Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.0 kB
0
Indexable
Never
#include <iostream>

unsigned long long fibonacciIterative( int n )
{
    if( n <= 1 )
    {
        return n;
    }

    unsigned long long fibNMinus2 = 0;
    unsigned long long fibNMinus1 = 1;
    unsigned long long fibN = 0;

    for( int i = 2; i <= n; ++i )
    {
        fibN = fibNMinus1 + fibNMinus2;
        fibNMinus2 = fibNMinus1;
        fibNMinus1 = fibN;
    }

    return fibN;
}

unsigned long long fibonacciRecursive( int n )
{
    if( n <= 1 )
    {
        return n;
    }
    return fibonacciRecursive( n - 1 ) + fibonacciRecursive( n - 2 );
}

int main()
{
    int n;
    std::cout << "Podaj n: ";
    std::cin >> n;

    unsigned long long result = fibonacciIterative( n );
    std::cout << n << "-ty wyraz ciagu Fibonacciego (iteracyjnie) to: " << result << std::endl;

    unsigned long long result2 = fibonacciRecursive( n );
    std::cout << n << "-ty wyraz ciągu Fibonacciego (rekurencyjnie) to: " << result2 << std::endl;

    return 0;
}

Leave a Comment