Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.


   J0 = 0
   J1 = 1
   Jn = Jn-1 + 2 × Jn-2


Terms may be calculated directly using one of several possible formulas:


   Jn = ( 2n - (-1)n ) / 3



Jacobsthal-Lucas numbers are very similar. They have the same recurrence relationship, the only difference is an initial starting value J0 = 2 rather than J0 = 0.

Terms may be calculated directly using one of several possible formulas:

   
   JLn = 2n + (-1)n
   

Jacobsthal oblong numbers is the sequence obtained from multiplying each Jacobsthal number Jn by its direct successor Jn+1.


Jacobsthal primes are Jacobsthal numbers that are prime.



Task
 Find and display the first 30 Jacobsthal numbers
 Find and display the first 30 Jacobsthal-Lucas numbers
 Find and display the first 20 Jacobsthal oblong numbers
 Find and display at least the first 10 Jacobsthal primes


See also
 Wikipedia: Jacobsthal number
 Numbers Aplenty - Jacobsthal number
 OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)
 OEIS:A014551 - Jacobsthal-Lucas numbers.
 OEIS:A084175 - Jacobsthal oblong numbers
 OEIS:A049883 - Primes in the Jacobsthal sequence
 Related task: Fibonacci sequence
 Related task: Leonardo numbers




use strict;
use warnings;
use feature <say state>;
use bigint;
use List::Util 'max';
use ntheory 'is_prime';
 
sub table { my $t = 5 * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
 
sub jacobsthal       { my($n) = @_; state  @J = (0, 1); do { push  @J,  $J[-1] + 2 *  $J[-2]} until  @J > $n;  $J[$n] }
sub jacobsthal_lucas { my($n) = @_; state @JL = (2, 1); do { push @JL, $JL[-1] + 2 * $JL[-2]} until @JL > $n; $JL[$n] }
 
my(@j,@jp,$c,$n);
push @j, jacobsthal $_ for 0..29;
do { is_prime($n = ( 2**++$c - -1**$c ) / 3) and push @jp, $n } until @jp == 20;
 
say "First 30 Jacobsthal numbers:\n",        table @j;
say "First 30 Jacobsthal-Lucas numbers:\n",  table map { jacobsthal_lucas $_-1 } 1..30;
say "First 20 Jacobsthal oblong numbers:\n", table map { $j[$_-1] * $j[$_]     } 1..20;
say "First 20 Jacobsthal primes:\n",         join "\n", @jp;