使用递归的 Ada 斐波那契数列

Kha*_*Ali 5 ada

在这段代码中,我试图编写一个程序,根据用户的输入(索引、大小)打印出斐波那契数列。然后,程序应该打印出 Index..Size 之间的所有斐波那契数。我在编写一个计算并打印出斐波那契数列的递归时遇到了麻烦。有什么建议?

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO, Ada.Unchecked_Deallocation;

procedure Fibonacci is
   type Arr is array (Positive range <>) of Integer;
   type Array_Access is access Arr;
   Size, Index : Positive;
   Variable    : Array_Access;
   procedure Free is new Ada.Unchecked_Deallocation (Arr, Array_Access);

   procedure Recursion (Item : Arr) is                  --Recursion
   begin
      Put_Line
        (Item (Item'First)'Image);                   --Prints out the numbers
      Recursion
        (Item
           (Item'First + Item'First + 1 ..
                Item'Last));     --Calculating the Fibonacci numbers
   end Recursion;

begin
   Put ("Welcome to the Fibonacci number series!");
   Put
     ("Enter an initial value and how many Fibonacci numbers you want to print: ");
   Get (Index);
   Get (Size);
   Variable := new Arr (Index .. Size);
   Recursion (Variable);
end Fibonacci;
Run Code Online (Sandbox Code Playgroud)

示例:输入指数(斐波那契数列的初始值):1
输入大小(要打印多少斐波那契数):5
前 5 个斐波那契数为:1 1 2 3 5

Sim*_*ght 8

来自维基百科

在数学中,斐波那契数列(通常表示为 F n)形成一个序列,称为斐波那契数列,其中每个数都是从 0 和 1 开始的前两个数的和。即
F 0 = 0
F 1 = 1

F n = F n - 1 + F n - 2

这很直接地翻译成

function Fibonacci (N : Natural) return Natural is
  (case N is
      when 0 => 0,
      when 1 => 1,
      when others => Fibonacci (N - 1) + Fibonacci (N - 2));
Run Code Online (Sandbox Code Playgroud)

或者,老式,

function Fibonacci (N : Natural) return Natural is
begin
   if N = 0 then
      return 0;
   elsif N = 1 then
      return 1;
   else
      return Fibonacci (N - 1) + Fibonacci (N - 2);
   end if;
end Fibonacci;
Run Code Online (Sandbox Code Playgroud)

您确实必须在函数之外进行打印,不可否认,重复计算较低结果的效率低下,但您并没有要求效率。


thi*_*dil 6

这是您的操作方法(此代码基于https://rosettacode.org/wiki/Fibonacci_sequence#Recursive

with Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure Fibonacci is

   First, Amount: Positive;

   function Fib(P: Positive) return Positive is --Recursion
   begin
      if P <= 2 then
         return 1;
      else
         return Fib(P-1) + Fib(P-2);
      end if;
   end Fib;

begin
   Ada.Text_IO.Put_Line("Welcome to the Fibonacci number series!");
   Ada.Text_IO.Put_Line("Enter an initial value and how many Kombinacci numbers you want to print: ");
   Ada.Integer_Text_IO.Get(First);
   Ada.Integer_Text_IO.Get(Amount);
   for I in First .. First + Amount loop
      Ada.Text_IO.Put("Fibonacci(" & Positive'Image(I) & " ) = ");
      Ada.Text_IO.Put_Line(Positive'Image(Fib(I)));
   end loop;
end Fibonacci;
Run Code Online (Sandbox Code Playgroud)

  • 我认为这比所需的数字多打印了一个? (2认同)
  • 是的,我的错。但该解决方案也存在一些性能问题,特别是在起始数较大或范围很长的情况下。另外,只有当您同意斐波那契数以 1 而不是 0 开头时,它才有效:) (2认同)