Peter
Peter Campbell Smith

Facto week

Weekly challenge 153 — 21 February 2022

Week 153: 21 Feb 2022

Task 2

Task — Factorions

You are given an integer, $n.

Write a script to figure out if the given integer is a factorion. A factorion is a natural number that equals the sum of the factorials of its digits.

Examples


Example 1:
Input: $n = 145
Output: 1
    Since 1! + 4! + 5! => 1 + 24 + 120 = 145

Example 2:
Input: $n = 123
Output: 0
    Since 1! + 2! + 3! => 1 + 2 + 6 <> 123

Analysis

I was tempted to submit

say 0;

which is nearly always correct. According to my algorithm 1, 2, 145 and 40585 are the only factorions under 100k, and these nice chaps at OEIS state that these are indeed the only 4 that exist. So

say $n =~ m/^(1|2|145|40585)$/ ? 1 : 0;

would do. However, since the task says we have to 'figure out' if the given number is a factorion I have written the relevant code.

Script


#!/usr/bin/perl

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

use v5.28;
use strict;
use utf8;

my (@tests, $test, $sum, @fac, $n, $not, $string1, $string2);

# numbers to test
@tests = (1, 2, 3, 4, 125, 145, 40585, 57778);

# calculate factorials of single digits
$fac[0] = 1;
for $n (1 .. 9) {
    $fac[$n] = $n * $fac[$n - 1];
}

# loop over tests
for $test (@tests) {
    $sum = 0;
    $string1 = $string2 = '';
    
    # test for being a factorion
    while ($test =~ m|(\d)|g) {
        $sum += $fac[$1];
        $string1 .= qq[$1! + ];
        $string2 .= qq[$fac[$1] + ];
    }
    
    # format output
    $string1 =~ s|...$||;
    $string2 =~ s|...$||;
    if ($sum == $test) {
        say qq[\nInput:  $test\nOutput: 1 since $string1 => $string2 = $test];
    } else {
        say qq[\nInput:  $test\nOutput: 0 since $string1 => $string2 = $sum <> $test];
    }
}

Output


Input:  1
Output: 1 since 1! => 1 = 1

Input:  2
Output: 1 since 2! => 2 = 2

Input:  3
Output: 0 since 3! => 6 = 6 <> 3

Input:  4
Output: 0 since 4! => 24 = 24 <> 4

Input:  125
Output: 0 since 1! + 2! + 5! => 1 + 2 + 120 = 123 <> 125

Input:  145
Output: 1 since 1! + 4! + 5! => 1 + 24 + 120 = 145

Input:  40585
Output: 1 since 4! + 0! + 5! + 8! + 5! => 24 + 1 + 120 + 40320 + 120 = 40585

Input:  57778
Output: 0 since 5! + 7! + 7! + 7! + 8! => 120 + 5040 + 5040 + 5040 + 40320 = 55560 <> 57778

 

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