Factorions

From Rosetta Code
Revision as of 12:51, 12 August 2019 by Chunes (talk | contribs) (Add Factor)
Factorions is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Definition

A factorion is a natural number that equals the sum of the factorials of its digits. For example 145 is a factorion in base 10 because:

   1! + 4! + 5! = 1 + 24 + 120 = 145.
Task

It can be shown (see Wikipedia article below) that no factorion in base 10 can exceed 1,499,999.

Write a program in your language to demonstrate, by calculating and printing out the factorions, that:

1. There are 4 factorions in base 10.

2. There are 3 factorions in base 9, 5 factorions in base 11 but only 2 factorions in base 12 up to the same upper bound as for base 10.

See also



Factor

<lang factor>USING: formatting io kernel math math.parser math.ranges memoize prettyprint sequences ; IN: rosetta-code.factorions

! Memoize factorial function MEMO: factorial ( n -- n! ) [ 1 ] [ [1,b] product ] if-zero ;

factorion? ( n base -- ? )
   dupd >base string>digits [ factorial ] map-sum = ;
show-factorions ( limit base -- )
   dup "The factorions for base %d are:\n" printf
   [ [1,b) ] dip [ dupd factorion? [ pprint bl ] [ drop ] if ]
   curry each nl ;

1,500,000 9 12 [a,b] [ show-factorions nl ] with each</lang>

Output:
The factorions for base 9 are:
1 2 41282 

The factorions for base 10 are:
1 2 145 40585 

The factorions for base 11 are:
1 2 26 48 40472 

The factorions for base 12 are:
1 2 

Go

<lang go>package main

import (

   "fmt"
   "strconv"

)

func main() {

   // cache factorials from 0 to 11
   var fact [12]uint64
   fact[0] = 1
   for n := uint64(1); n < 12; n++ {
       fact[n] = fact[n-1] * n
   }
   for b := 9; b <= 12; b++ {
       fmt.Printf("The factorions for base %d are:\n", b)
       for i := uint64(1); i < 1500000; i++ {
           digits := strconv.FormatUint(i, b)
           sum := uint64(0)
           for _, digit := range digits {
               if digit < 'a' {
                   sum += fact[digit-'0']
               } else {
                   sum += fact[digit+10-'a']
               }
           }
           if sum == i {
               fmt.Printf("%d ", i)
           }
       }
       fmt.Println("\n")
   }

}</lang>

Output:
The factorions for base 9 are:
1 2 41282 

The factorions for base 10 are:
1 2 145 40585 

The factorions for base 11 are:
1 2 26 48 40472 

The factorions for base 12 are:
1 2