Home > database >  recursive function in c for the furmula: a(n)=a(n-1) a(n-2)
recursive function in c for the furmula: a(n)=a(n-1) a(n-2)

Time:05-30

I am trying to write a recursive function for the formula:
a(n)=a(n-1) a(n-2)
I've tried to simply write it out:

 unsigned int ladder(unsigned int n)
{
    unsigned int ret=0;
    if (n < 1)
        return ret;
    ret = ladder(n - 1)   ladder(n - 2);


}

but it goes into stack overflow when calling for ladder(n-2)
(for some reason it sets n as a very large integer)

I feel like I'm missing something very basic but can't figure out what.

CodePudding user response:

The function returns nothing in case when n is not less than 1.

Also when n is equal to 1 then the expression n - 2 yields the maximum value that can be stored in object of the type unsigned int.

The function can be declared and defined the following way

unsigned long long int ladder( unsigned int n )
{
    return n < 2 ? n : ladder( n - 1 )   ladder( n - 2 );
}

Here is a demonstration program.

#include <stdio.h>

unsigned long long int ladder( unsigned int n )
{
    return n < 2 ? n : ladder( n - 1 )   ladder( n - 2 );
}

int main( void )
{
    for ( unsigned int i = 0; i < 25; i   )
    {
        printf( "%llu ", ladder( i ) );
    }
    putchar( '\n' );
}

The program output is

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 
  • Related