0

Hi there sorry for this noob question. I'm Mario and may I ask if my program is correct for recursive and non-recursive function for Fibonacci Secquence nth Value.

static int recursiveMethod(int num) 
{ 
if (num <= 1) 
   return num; 
return recursiveMethod(num-1) + recursiveMethod(num-2); 
}

static int nonRecursiveMethod(int num) { 
    if (num == 0) { 
        return 0; 
    }

    if (num == 1) {
        return 1; 
    } 
    int first = 0; 
    int second = 1; 
    int nth = 1; 
    for (int i = 2; i <= num; i++) { 
        nth = first + second;
        first = second;
        second = nth;
    } 
    return nth;
}

For summary: Example I inputted 6 as my nth value. Then the outputs are RECURSIVE: 8 then NON-RECURSIVE: 1 1 2 3 5 8

Is that correct?

  • This question belongs to https://codereview.stackexchange.com/ – Arvind Kumar Avinash Apr 03 '20 at 12:00
  • 1
    @ArvindKumarAvinash: Please have a look at the [help center](https://codereview.stackexchange.com/help/on-topic) there. Checking if the program is implemented correctly is not on-topic at Code Review, only reviewing code that works is. – Graipher Apr 03 '20 at 12:27

2 Answers2

0

Calling nonRecursiveMethod will produce the same output as calling recursiveMethod. The result is correct, recursiveMethod is inefficient for big numbers, though, because it will compute results for lower numbers again and again.

tobi
  • 1,205
  • 2
  • 8
  • 8
0

yeah both the approaches are fine. What I would like to suggest here is rather than calling function for every "num" you can pre-compute and store the values(Dynamic Programming).