Go 練習問題
Fibonacci Sequence in Go
Build the Fibonacci numbers with a loop, a double assignment and a slice.
学べること
- 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.
重要なポイント
- Start from 0 and 1.
- One assignment moves both values.
- uint64 holds much larger numbers than int32.
実行できる Go のサンプル
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: 7778742049練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ