Difference between revisions of "Fibonacci number/ru"

From Lazarus wiki
Jump to navigationJump to search
(Created page with "{{Fibonacci_number}} = Числа Fibonacci = Числа Fibonacci задаются следующей последовательностью: 0, 1, 1, 2, 3, 5, 8, 13, 21,...")
 
m (Fixed syntax highlighting; deleted category included in page template)
 
Line 11: Line 11:
 
== Рекурсивный способ ==
 
== Рекурсивный способ ==
  
<syntaxhighlight>
+
<syntaxhighlight lang=pascal>
  
 
function FibonacciNumber( n : integer ): integer;
 
function FibonacciNumber( n : integer ): integer;
Line 26: Line 26:
 
Вот один из предпочтительных вариантов.
 
Вот один из предпочтительных вариантов.
  
<syntaxhighlight>
+
<syntaxhighlight lang=pascal>
 
 
 
function Fibonacci(n: Integer): Integer;
 
function Fibonacci(n: Integer): Integer;
 
var
 
var
Line 52: Line 51:
 
   
 
   
 
* [http://www.freepascal.org/docs-html/prog/progsu151.html  Some assembly routine which uses the C calling convention that calculates the nth Fibonacci number]  
 
* [http://www.freepascal.org/docs-html/prog/progsu151.html  Some assembly routine which uses the C calling convention that calculates the nth Fibonacci number]  
* [[Solution_3| Tao Yue Solution to Fibonacci Sequence Problem]]
+
* [[Solution_3| Tao Yue Solution to Fibonacci Sequence Problem]]
 
 
[[Category:Mathematics]]
 

Latest revision as of 23:13, 14 February 2020

Deutsch (de) English (en) suomi (fi) français (fr) русский (ru)

Числа Fibonacci

Числа Fibonacci задаются следующей последовательностью:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Идея заключается в сложении двух последних чисел, и этот результат является следующим значением последовательности.

Рекурсивный способ

function FibonacciNumber( n : integer ): integer;
begin
  if n > 1 then result := ( FibonacciNumber( n - 1 ) + FibonacciNumber( n - 2 ) )
    else
      if n = 0 then result := 0
        else result := 1;
end;

Итеративный способ

Вот один из предпочтительных вариантов.

function Fibonacci(n: Integer): Integer;
var
  i,u,v,w: Integer;
begin
  if n <= 0 then
    exit(0);
  if n = 1 then 
     exit(1);
  u := 0;
  v := 1;
  for i := 2 to n do 
  begin
    w := u + v;
    u := v;
    v := w;
  end;
  Result := v;
End;

См. также