Monday, April 15, 2024
HomeSoftware EngineeringHow you can Discover the Final Fibonacci Digit in Golang

How you can Discover the Final Fibonacci Digit in Golang

The problem#

Return the final digit of the nth ingredient within the Fibonacci sequence (beginning with 1,1, to be additional clear, not with 0,1 or different numbers).

``````LastFibDigit(1) == 1
LastFibDigit(2) == 1
LastFibDigit(3) == 2
LastFibDigit(1000) == 5
LastFibDigit(1000000) == 5
``````

Choice 1:

``````package deal answer
func LastFibDigit(n int) int {
n %= 60
a, b := 0, 1
for i := 0; i<n; i++ { a, b = b, a+b }
return a % 10
}
``````

Choice 2:

``````package deal answer
func LastFibDigit(n int) int {
fib := []int{0, 1}
for i := 1; i < 60; i++ {
fib = append(fib, (fib[i]+fib[i-1])%10)
}
j := n % 60
return fib[j]
}
``````

Choice 3:

``````package deal answer
import "math"
func LastFibDigit(n int) int {
return int(math.Pow(math.Phi, float64(npercent60))/math.Sqrt(5) + 0.5) % 10
}
``````

Check circumstances to validate our answer#

``````package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Pattern take a look at circumstances", func() {
It("Fundamental assessments", func() {
Anticipate(LastFibDigit(1)).To(Equal(1))
Anticipate(LastFibDigit(21)).To(Equal(6))
Anticipate(LastFibDigit(302)).To(Equal(1))
Anticipate(LastFibDigit(4003)).To(Equal(7))
Anticipate(LastFibDigit(50004)).To(Equal(8))
Anticipate(LastFibDigit(600005)).To(Equal(5))
Anticipate(LastFibDigit(7000006)).To(Equal(3))
Anticipate(LastFibDigit(80000007)).To(Equal(8))
Anticipate(LastFibDigit(900000008)).To(Equal(1))
Anticipate(LastFibDigit(1000000009)).To(Equal(9))
})
})
``````
RELATED ARTICLES