DEV Community

Cover image for My solution to Code challenge #77
Victor Avelar
Victor Avelar

Posted on

My solution to Code challenge #77

Implemented in golang, quite easy to be fair ๐Ÿ˜„

func GetNthFib(n int) int {
    if n == 1 {
        return 0
    }
    if n == 2 {
        return 1
    }
    x, y := 0, 1
    for i := 2; i < n; i++ {
        x, y = y, x+y
    }
    return y
}
Enter fullscreen mode Exit fullscreen mode

Explanation

So we check for the first two value as this two are required to be able to build the rest of the sequence.

Once we know it is not 0 (x) or 1 (y), we know that the correct result comes from adding the x+y and moving the values 1 place forward.

The loop starts at 2 because otherwise the results will be offset by 2 iterations (we already check the first two statically).

For example, if the loop starts at 0 and they ask for nth 3, then our result will be 3 which is incorrect as the third position on Fibonacci's sequence is 1.

You can play around with it by using this Golang Playground link

Top comments (1)

Collapse
 
evgenijrenke profile image
Evgenij Renke • Edited

Your solution is not correct.
Fibonacci is defined:
Fib(0) = 0
(zero and negative n are more or less optional, depending on your requirements/definition)

Fib(1) = 1
Fib(2) = 1
Fib(n) = (n-1)+(n-2)

Your solution:
Fib(0) = 1
Fib(1) = 0
Fib(2) = 1
Fib(3) = 1
Fib(4) = 2
...

Here is a quick fix:

package main

import (
    "fmt"
)

func main() {
    fmt.Println(getNthFib(4))
}

func getNthFib(n int) int {
    if n == 0 {
        return 0 
    }
    if n == 1 {
        return 1 // x=1
    }

    // this if is theoretical not necessary in this code 
    // because y := 1 -> skip for loop -> directly return y
    // but better for Readability and clean code 
    if n == 2 {
        return 1 // y=1
    }

    x, y := 1, 1
    for i := 2; i < n; i++ {
        x, y = y, x+y
    }
    return y
}