My solution to Code challenge #77

twitter logo github logo ・1 min read

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
}

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

twitter logo DISCUSS (2)
markdown guide
 

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
}
 

Here is a challenge for you. Can you do it in recursive way?

Classic DEV Post from Jul 27

If You Don't Know, Now You Know - GitHub Is Restricting Access For Users From Iran And A Few Other Embargoed Countries

Please help our cause against modern-day discrimination

Victor Hugo Avelar profile image
Software engineer at trivago. 27, Mexican living in Germany.