Rust अभ्यास
Fibonacci Sequence in Rust
Build the Fibonacci numbers with a loop, a tuple swap and a vector.
आप क्या सीखेंगे
- A loop with two variables
- (a, b) = (b, a + b)
- Why u64
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 vector.
a and b hold two neighbouring numbers. (a, b) = (b, a + b) moves both one step forward in a single assignment. u64 is used because Fibonacci numbers grow quickly: the 50th no longer fits in 32 bits.
मुख्य बातें
- Start from 0 and 1.
- One tuple assignment moves both values.
- u64 holds much larger numbers than u32.
चलने योग्य Rust उदाहरण
Rust
main.rs
fn fibonacci(count: usize) -> Vec<u64> {
let mut sequence = Vec::with_capacity(count);
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..count {
sequence.push(a);
(a, b) = (b, a + b);
}
sequence
}
fn main() {
println!("{:?}", fibonacci(10));
println!("50th: {}", fibonacci(50)[49]);
}
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
50th: 7778742049अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- फिबोनाच्ची संख्या n-वीं फिबोनाच्ची संख्या लौटाएँ। आसान
- सम_even_फिबोनाच्ची_पदों_का_योग उन सम फिबोनाच्ची पदों को जोड़ें जो एक सीमा से अधिक नहीं हैं। आसान