Friday, February 24, 2023
HomeSoftware EngineeringMethods to Discover the Final Fibonacci Digit in Golang

Methods to Discover the Final Fibonacci Digit in Golang


The problem

Return the final digit of the nth component 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

The answer in Golang

Choice 1:

package deal resolution
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 resolution
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 resolution
import "math"
func LastFibDigit(n int) int {
  return int(math.Pow(math.Phi, float64(npercent60))/math.Sqrt(5) + 0.5) % 10
}

Check instances to validate our resolution

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments