Search code examples
mathdigitslargenumberapl

Factorial digit sum in APL (Project Euler 20)


First I found +/⍎¨⍕(!8) and it gave me the result 9. But if I do 100!, as the number is big, I am not able to get that.

With ⍎¨⍕(!100) I am getting a syntax error: ⍎SYNTAX ERROR

Is there any other way to solve the problem or can you suggest me some modifications?


Solution

  • !100 is a large number and when you format it's result you'll get a string representing a number in E notation.

    ⍕!100'9.332621544E157', when you attempted to eval () each character you ran into a syntax error since E has no meaning.

    There are two ways to split a large integer into it's digits:

    Firstly with inverse decode, examples can be found on the APLcart

        10⊥⍣¯1!100
    

    This is vulnerable to floating point imprecision, however.

    The second and preferred option is using big from the dfns library, which can be imported using the quad function CY.

    'big'⎕CY'dfns'

    Examples here

    And thankfully the last example covers your exact case! Factorial 100 is ↑×big/⍳100

    The final solution to the problem could look like this:

    +/⍎¨↑×big/⍳100