How to Find the Last Fibonacci Digit in Golang

0 min read 174 words

The challenge

Return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).

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

The solution in Golang

Option 1:

package solution
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
}

Option 2:

package solution
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]
}

Option 3:

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

Test cases to validate our solution

package solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Sample test cases", func() {
  It("Basic tests", func() {
    Expect(LastFibDigit(1)).To(Equal(1))
    Expect(LastFibDigit(21)).To(Equal(6))
    Expect(LastFibDigit(302)).To(Equal(1))
    Expect(LastFibDigit(4003)).To(Equal(7))
    Expect(LastFibDigit(50004)).To(Equal(8))
    Expect(LastFibDigit(600005)).To(Equal(5))
    Expect(LastFibDigit(7000006)).To(Equal(3))
    Expect(LastFibDigit(80000007)).To(Equal(8))
    Expect(LastFibDigit(900000008)).To(Equal(1))
    Expect(LastFibDigit(1000000009)).To(Equal(9))
  })
})
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts