Exercícios de Go
Fibonacci Sequence in Go
Build the Fibonacci numbers with a loop, a double assignment and a slice.
O que você vai aprender
- A loop with two variables
- a, b = b, a+b
- Why uint64
The first numbers
00
11
12
23
34
55
Each number is the sum of the two before
Each Fibonacci number is the sum of the two before it, starting from 0 and 1. Build the first numbers of the sequence in a slice.
a and b hold two neighbouring numbers. a, b = b, a+b moves both one step forward in a single assignment. uint64 is used because Fibonacci numbers grow quickly: the 50th no longer fits in 32 bits.
Pontos-chave
- Start from 0 and 1.
- One assignment moves both values.
- uint64 holds much larger numbers than int32.
Exemplo executável de Go
main.go
package main
import "fmt"
func fibonacci(count int) []uint64 {
sequence := make([]uint64, 0, count)
a, b := uint64(0), uint64(1)
for i := 0; i < count; i++ {
sequence = append(sequence, a)
a, b = b, a+b
}
return sequence
}
func main() {
fmt.Println(fibonacci(10))
fmt.Println("50th:", fibonacci(50)[49])
}
[0 1 1 2 3 5 8 13 21 34]
50th: 7778742049Pratique
Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.
Terminou esta lição?
Marque como aprendida para acompanhar seu progresso.
Seu progresso está salvo neste navegador Entre para mantê-lo em todos os dispositivos.
Pratique com um desafio
Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.
- Número de Fibonacci Retorne o n-ésimo número de Fibonacci. Fácil
- Somar Termos Pares de Fibonacci Some os termos pares da sequência de Fibonacci que não excedem um limite. Fácil