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 उदाहरण
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 रिव्यू के साथ।
- फिबोनाच्ची संख्या n-वीं फिबोनाच्ची संख्या लौटाएँ। आसान
- सम_even_फिबोनाच्ची_पदों_का_योग उन सम फिबोनाच्ची पदों को जोड़ें जो एक सीमा से अधिक नहीं हैं। आसान