The Recamán's sequence generates Natural numbers.

Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.


If the conditions don't hold then a(n) = a(n-1) + n.



Task

 Generate and show here the first 15 members of the sequence.
 Find and show here, the first duplicated number in the sequence.
 Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.


References

 A005132, The On-Line Encyclopedia of Integer Sequences.
 The Slightly Spooky Recamán Sequence, Numberphile video.
 Recamán's sequence, on Wikipedia.


use bignum;
 
$max = 1000;
$remaining += $_ for 1..$max;
 
my @recamans = 0;
my $previous = 0;
 
while ($remaining > 0) {
   $term++;
   my $this = $previous - $term;
   $this = $previous + $term unless $this > 0 and !$seen{$this};
   push @recamans, $this;
   $dup = $term if !$dup and defined $seen{$this};
   $remaining -= $this if $this <= $max and ! defined $seen{$this};
   $seen{$this}++;
   $previous = $this;
}
 
print "First fifteen terms of Recaman's sequence: " . join(' ', @recamans[0..14]) . "\n";
print "First duplicate at term: a[$dup]\n";
print "Range 0..1000 covered by terms up to a[$term]\n";