Bài tập Go

Fibonacci Sequence in Go

Build the Fibonacci numbers with a loop, a double assignment and a slice.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • A loop with two variables
  • a, b = b, a+b
  • Why uint64
The first numbers
00
11
12
23
34
55
5 = 2 + 3

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.

Những điểm quan trọng

  1. Start from 0 and 1.
  2. One assignment moves both values.
  3. uint64 holds much larger numbers than int32.

Ví dụ Go chạy được

Go
Chạy code →
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])
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
[0 1 1 2 3 5 8 13 21 34]
50th: 7778742049

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Structs →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách