Peter
Peter Campbell Smith

Facto week

Weekly challenge 153 — 21 February 2022

Week 153 - 21 Feb 2022

Task 1

Task — Left factorials

Write a script to compute Left Factorials of 1 to 10. Please refer OEIS A003422 for more information.

Examples


Example 1:
!4 = 0! + 1! + 2! + 3!
   = 1  + 1  + 2  + 6
   = 10   

Analysis

We are referred to the OEIS for a definition, which is given as:

!n = Sum_{k=0..n-1} k! 

A little thought shows that can also be expressed as:

!n = !(n-1) + (n-1)! 

which is pleasingly symmetrical and also (marginally) more efficient when we're generating the numbers sequentially.

But even with my rather verbose style of coding my solution is only 7 lines of code.

Try it 

Try running the script with any input:



example: 15

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-02-21
# PWC 153 task 1

use v5.28;
use strict;
use utf8;

my ($n, $string, @lf, @fac);

# assume !1 and 1!
$lf[1] = 1;
$fac[1] = 1;

# calculate the rest as per the third comment line above
for $n (2 .. 10) {
    $lf[$n] = $lf[$n - 1] + $fac[$n - 1];
    $fac[$n] = $fac[$n - 1] * $n;
    say qq[!$n = $lf[$n]];
}

Output


!2 = 2
!3 = 4
!4 = 10
!5 = 34
!6 = 154
!7 = 874
!8 = 5914
!9 = 46234
!10 = 409114

The content of this website which has been created by
Peter Campbell Smith is hereby placed in the public domain