diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-01-27 16:43:04 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-01-27 16:43:04 +0000 |
| commit | 8fbc7289ae1187bc90e4cfe9d8e259505cfd0870 (patch) | |
| tree | cedd423ad6ab1f9b19aa35a96acf0512c350a702 | |
| parent | 37205badad4c33db23e01dbdefeacee5bc6c35d3 (diff) | |
| parent | d85d0991c761917112c9806f0b2f7069431be1cd (diff) | |
| download | perlweeklychallenge-club-8fbc7289ae1187bc90e4cfe9d8e259505cfd0870.tar.gz perlweeklychallenge-club-8fbc7289ae1187bc90e4cfe9d8e259505cfd0870.tar.bz2 perlweeklychallenge-club-8fbc7289ae1187bc90e4cfe9d8e259505cfd0870.zip | |
Merge pull request #5570 from PerlBoy1967/branch-for-challenge-149
Task 1
| -rwxr-xr-x | challenge-149/perlboy1967/perl/ch-1.pl | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/challenge-149/perlboy1967/perl/ch-1.pl b/challenge-149/perlboy1967/perl/ch-1.pl new file mode 100755 index 0000000000..1b26cca576 --- /dev/null +++ b/challenge-149/perlboy1967/perl/ch-1.pl @@ -0,0 +1,66 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 149 + - https://perlweeklychallenge.org/blog/perl-weekly-challenge-149/#TASK1 + +Author: Niels 'PerlBoy' van Dijke + +TASK #1 › Fibonacci Digit Sum +Submitted by: Roger Bell_West + +Given an input $N, generate the first $N numbers for which the sum of their +digits is a Fibonacci number. + +=cut + +use v5.16; + +use List::Util qw(sum); +use Memoize; +use Data::Printer output => 'stdout'; + +# Prototypes +sub isFibonacciDigitSum($); +sub fibonacci ($); + +memoize('fibonacci'); + +my ($N) = @ARGV; $N //= 20; + +die "Input must be integer value and >= 1" + unless (defined $N and $N =~ m#^[1-9][0-9]*$# and $N >= 1); + +my @solutions; + +my $n = 0; +while(scalar(@solutions) < $N) { + push(@solutions, $n) if (isFibonacciDigitSum($n)); + $n++; +} + +p @solutions; + +sub isFibonacciDigitSum ($) { + my ($n) = @_; + + state @fib; + state %fib; + + my $digitSum = sum(split(//, $n)); + while (scalar(@fib) == 0 or $fib[-1] <= $digitSum) { + push(@fib, fibonacci(scalar(@fib))); + $fib{$fib[-1]}++; + } + + return exists $fib{$digitSum} ? 1 : 0; +} + +sub fibonacci ($) { + my ($n) = @_; + + return 0 if ($n == 0); + return 1 if ($n == 1 or $n == 2); + return fibonacci($n - 1) + fibonacci($n - 2); +} |
