The Fibonacci Perl program exits memory even for small inputs, even after using Memoization,

Program:

use warnings;
use Memoize;
memoize ('F');

sub F{
 $n = shift;
 return 0 if $n==0;
 return 1 if $n ==1;
 return F($n-1)+F($n-2);
}

print F(10);

Even for a small value - F (3), F (2), I get this error:

Deep recursion on anonymous subroutine at 5.pl line 13.
Out of memory!
+4
source share
1 answer

$n - , . , ( ) , , . , . , . a print "$n\n"; shift, , $n 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, -1, - 2, -3 .. .

, :

use strict;
use warnings;
use Memoize;
memoize('F');

sub F{
  my $n = shift; # Notice "my", creating an instance of $n lexically scoped
                 # to the subroutine. A new instance is tracked for each call.
  return 0 if $n == 0;
  return 1 if $n == 1;
  return F($n-1)+F($n-2);
}

print F(10), "\n";

55.

, , , ( my), , my , , , , .

+14

Source: https://habr.com/ru/post/1629745/


All Articles