MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Formula

Function Formula

math/fibonacci/fibonacci.go:44–49  ·  view source on GitHub ↗

Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio) Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers

(n uint)

Source from the content-addressed store, hash-verified

42// Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio)
43// Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers
44func Formula(n uint) uint {
45 sqrt5 := math.Sqrt(5)
46 phi := (sqrt5 + 1) / 2
47 powPhi := math.Pow(phi, float64(n))
48 return uint(powPhi/sqrt5 + 0.5)
49}
50
51// Recursive calculates the n-th fibonacci number recursively by adding the previous two Fibonacci numbers.
52// This algorithm is extremely slow for bigger numbers, but provides a simpler implementation.

Callers 2

TestFormulaFunction · 0.85
BenchmarkFormulaFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestFormulaFunction · 0.68
BenchmarkFormulaFunction · 0.68