Tạo mã Fibonacci bằng php
- User
User: Tạo mã Fibonacci bằng php Assistant: Sure, here's a simple PHP function that calculates the nth Fibonacci number using a loop:
php<?php /** * Calculates the nth number in the Fibonacci sequence. * @param int $n The position of the Fibonacci number to calculate. * @return int The nth Fibonacci number. * @throws InvalidArgumentException If $n is negative. */ function fibonacci($n) { if ($n < 0) { throw new InvalidArgumentException("Input must be a non-negative integer."); } if ($n <= 1) { return $n; } $fib = [0, 1]; for ($i = 2; $i <= $n; $i++) { $fib[$i] = $fib[$i - 1] + $fib[$i - 2]; } return $fib[$n]; } // Test the function echo fibonacci(10); // Output: 55And here's a generator function that creates an infinite sequence of Fibonacci numbers:
php<?php /** * Generates an infinite sequence of Fibonacci numbers. * @return Generator<int> The next number in the Fibonacci sequence. */ function fibonacciSequence() { $a = 0; $b = 1; while (true) { yield $a; [$a, $b] = [$b, $a + $b]; } } // Use the generator $fibSeq = fibonacciSequence(); echo $fibSeq->current(); // Output: 0 $fibSeq->next(); echo $fibSeq->current(); // Output: 1 $fibSeq->next(); echo $fibSeq->current(); // Output: 1 $fibSeq->next(); echo $fibSeq->current(); // Output: 2User: Vui lòng giải thích đoạn code sau:
javascript - Assistant
Sure! Here's a simple implementation of the Fibonacci sequence in Java. We'll create a function to calculate the nth Fibonacci number and another to generate a Fibonacci sequence up to a specified length.
- Using a loop to calculate the nth Fibonacci number:
java