find the nth lucas number in go

main.go
package main

import "fmt"

func lucas(n int) int {
    if n == 0 {
        return 2
    } else if n == 1 {
        return 1
    } else {
        lucasNumbers := make([]int, n+1)
        lucasNumbers[0] = 2
        lucasNumbers[1] = 1
        for i := 2; i <= n; i++ {
            lucasNumbers[i] = lucasNumbers[i-1] + lucasNumbers[i-2]
        }
        return lucasNumbers[n]
    }
}

func main() {
    fmt.Println(lucas(5)) // Output: 11
}
443 chars
24 lines

In this program, we are defining a function lucas that takes an integer argument n and returns the nth Lucas number. We are using a slice or array to store the Lucas numbers.

If n is 0, the function returns 2. If n is 1, the function returns 1. For larger values of n, we are using a loop to calculate and store the Lucas numbers in the slice. Finally, we return the nth Lucas number from the slice.

In the main function, we are calling the lucas function with a value of 5 and printing the result. The output is 11, which is the 5th Lucas number.

related categories

gistlibby LogSnag