g | x | w | all
Bytes Lang Time Link
051Janet250507T204805Zxigoi
047Juby250507T184141ZJordan
048Perl 5 MListUtil=product250507T201743ZXcali
024CASIO BASIC CASIO fx9750GIII250507T190457Zmadeforl
029x8664 machine code230711T172912Zengineer
031Haskell230422T155427ZWheat Wi
012Pip230416T105644ZThe Thon
023Julia 0.7230420T184903ZKirill L
049Zsh230420T022835ZGammaFun
025Raku230420T003439ZJo King
005Pyth230419T152054ZCursorCo
054Rust230418T145629ZJSorngar
015Ohm v2230417T231333ZCliff
039FunStack alpha230417T214107ZDLosc
064BrainFlak230417T200428ZNitrodon
510Nibbles230416T175152ZDominic
004Oasis230417T085421ZKevin Cr
011Brachylog230417T091714ZFatalize
00405AB1E230417T083553ZKevin Cr
006APLDyalog Unicode230416T195930Zuser1172
007MATL230416T195337Zbeaker
032C gcc230416T181158ZNoodle9
020Wolfram Language Mathematica230416T171750Zatt
006Thunno 2230416T104938ZThe Thon
031R230416T080743ZDominic
004Japt230416T115536ZShaggy
5342><> Fish230416T065608Zmousetai
4035PARI/GP230416T011001Z138 Aspe
022minigolf230416T003327Zuser1176
048Curry PAKCS230416T090911Zlesobrod
028JavaScript ES6230415T223202ZArnauld
010J230416T081323Zsouth
038Excel230416T051914ZJos Wool
040Python230416T031658Zloopy wa
028Desmos230416T020210ZAiden Ch
054Retina230416T010747ZNeil
010Pyt230415T235504ZKip the
020Wolfram Language Mathematica230415T233946ZUnmitiga
012Charcoal230415T232725ZNeil
004Jelly230415T223744ZJonathan
004Vyxal230415T224135Zlyxal
006Jelly230415T222758Zcaird co

Janet, 51 bytes

|(reduce|(-(*;(map|(+ $ 2)(range $1)))$)0(range $))

J-uby, 47 bytes

:+|:*&(:+|:/&:*)|:~|~:zip&[1,-1].cycle|:sum++:*

Attempt This Online!

Explanation

:+ | :* & (:+ | :/ & :*) | :~ | ~:zip & [1,-1].cycle | :sum + +:*

:+ |                    # Range 1..input
* & (            ) |    # Map with...
     :+ | :/ & :*       #   Range 1..n reduced by multiplication
:~ |                    # Reverse, then
~:zip & [1,-1].cycle |  # Zip with endless list [1,-1,1,-1,...], then
:sum + +:*              # Sum products of zipped pairs

Perl 5 -MList::Util=product,sum -pa, 48 bytes

$_=1*sum map{(-1)**("@F"-$_)*product 1..$_}1..$_

Try it online!

CASIO BASIC (CASIO fx-9750GIII), 24 bytes

?→N
Σ((-1)^(N-I)I!,I,1,N

is exactly the equation

x86-64 machine code, 29 bytes

Uses standard System V ABI with signature long afact(int n). The input n is taken in rdi, and the output is given in rax.

31 c0 85 ff 74 16 ff c0 57 59 48 f7 e1 e2 fb 50 ff cf e8 e9 ff ff ff 48 29 04 24 58 c3

Try it online!

Explanation

The function implements the recurrence relation \$\operatorname{af}(n)\$ as given in the question.

afact:
    ; clear rax
    xor eax, eax

    ; return if n=0
    test edi, edi
    jz __afact_retn

    ; factorial first
    ; set eax to 1
    inc eax
    
    ; n into rcx
    push rdi
    pop rcx

    ; n times:
__afact_flp:
    ; rax *= n(--)
    mul rcx
    loop __afact_flp
    
    ; n! is in rax
    ; save it
    push rax
    
    ; get afact(n-1) in rax
    dec edi
    call afact

    ; subtract rax from qword [rsp] (n!)
    sub qword [rsp], rax
    
    ; pop and return
    pop rax

__afact_retn:
    ret

Haskell, 31 bytes

x!1=abs x
x!y=(1-x*y)!(y-1)
(0!)

Attempt This Online!

Pip, 17 16 12 bytes

$* *\,\,aFDv

Attempt This Online!

Port of Jonathan Allan's Jelly answer.

-4 thanks to @DLosc

Explanation

$* *\,\,aFDv   ; Input on command line
      \,a      ; Range from 1 to input
    \,         ; Range from 1 to each
$* *           ; Product of each inner list
         FDv   ; From a list of digits in base -1
               ; Implicit output

Old:

({$*\,a}M\,a)FDv   ; Input on command line
         \,a       ; Range from 1 to input
 {     }M          ; Map over this list:
  $*               ;   Product of...
    \,a            ;   ...range from 1 to the number
(           )FD    ; Convert from a list of digits...
               v   ; ...in base -1
                   ; Implicit output

Julia 0.7, 23 bytes

!n=n>0?prod(1:n)-!~-n:0

Try it online!

Uses the recursive formula.

Zsh, 49 bytes

r=i=$[$1>0]
for n ({$1..2})((r=r*n+(i=-i)))
<<<$r

Try it online!

This turned into a super interesting problem, because managing the right base cases for a recursive solution takes too many bytes. Instead, I came up with an equivalent form:

$$ \mbox{af}(n)=\mbox{af}'(1,-1,n)=\begin{cases} r,i,0 :& 0 \\ r,i,1 :& r \\ r,i,n :& \mbox{af}'(r\cdot n+i,-i,n-1) \end{cases} $$

There's probably a way to make both this form and the program shorter. I had to use r=i=$[$1>0] instead of r=i=1 to get the \$ n=0 \$ case, otherwise this program will output -1. Also, you may notice that since my program uses a range between $1 and 2, that it doesn't follow the recursion above for \$n = 1\$. It turns out, looping upwards to 2 results in \$(1\cdot 1 -1)\cdot 2 + 1 = 1\$, so it all works out okay.

Raku, 25 bytes

{[[&(&[R-])]] [\*] 1..$_}

Try it online!

There has got to be a better way of doing that second reduce. For reference, the [op] means reduce, the \ means keep the intermediate values, and the R metaoperator reverses the order of the subtraction. So [\*] the range 1 to input will return a list of factorials from 1 to input. From this we want to fold right over the list with reversed subtraction, which would be [R-] right? However R- also has reversed precedence, so a R- b R- c is equivalent to c - b - a rather than c - (b - a). So we have to make it a function rather than an operator with &[R-], but inserting it into the reduction operator requires an extra pair of []s as well as an &() for some reason (but *R-* also doesn't work for reasons). This bloats it up to the point where reduce &[R-] is now the same length, blergh.

Alternatively, we can construct a sequence and index into it:

Raku, 30 bytes

-1 byte thanks to Steffan

{(0,{abs $_-=$*=++$}...*)[$_]}

Try it online!

If this IO method ends up allowed as default, then this can be shortened to 23 bytes.

Pyth, 5 bytes

aF.!S

Try it online!

Explanation

aF.!SQ    # implicitly add Q
          # implicitly assign Q = eval(input())
    SQ    # inclusive range from 1 to Q
  .!      # map to factorial
aF        # fold over the absolute difference

Rust, 54 bytes

fn a(n:i64)->i64{if n<2{n}else{n*a(n-2)+(n-1)*a(n-1)}}

All my attempts at golfing this straightforward recursive solution just made the code longer, so I welcome any help!

Attempt This Online!

Ohm v2, 15 bytes

?@(!1→ρΓ³#R(ⁿ*Σ

Try it online!

Ohm is very weird. It thinks that the factorial of 1 is nil, doesn't do base conversion from -1 like other answers and doesn't like formatting numbers correctly sometimes.

Explained

?@(!1→ρΓ³#R(ⁿ*Σ
?     # only execute this program if the input is not 0
@(    # the range 2..input
!     # factorial of each
1→ρ  # append 1 to that and rotate right. This is because `1!` gives nil
Γ     # Push -1
³#R(  # range(0, n - 1)[::-1]
ⁿ     # -1 to the power of each of those numbers 
Σ     # summed.

FunStack alpha, 39 bytes

Minus foldl 0 Product map IFrom1 IFrom1

Try it at Replit!

Worked example

                4
IFrom1          [1,2,3,4]
IFrom1          [[1],[1,2],[1,2,3],[1,2,3,4]]
Product map     [1,2,6,24]
Minus foldl 0   19

where the last bit is

Minus          Subtract first argument from second
      foldl    Left-fold on that function
            0  starting with an accumulator value of 0

and so our result is -(-(-(-0+1)+2)+6)+24 = 19.

Brain-Flak, 64 bytes

{(({})[()]<({([{}]()({}))([{}]({}))}{}{}([{}])((){}))>)}{}({}<>)

Try it online!

This does not compute any factorials as intermediate results. Instead, it multiplies by successively smaller numbers and either adds or subtracts one. Sample calculation for the alternating factorial of 5:

0  *6 +1 = 1
1  *5 -1 = 4
4  *4 +1 = 17
17 *3 -1 = 50
50 *2 +1 = 101

Nibbles, 5.5 5 bytes (10 nibbles)

Edit: -0.5 bytes (1 nibble) thanks to xigoi

/.\,$`*,$-

Attempt This Online!

Port of my R answer.

/.\,$`/,$*-
 .          # map over
  \         # reverse of 
   ,$       # 1..input:
     `*     #   product of
       ,$   #   1..each element
            # (at this point we have list of
            # factorials in reverse order);
/           # now, fold over this from right to left
         -  # by subtraction

Oasis, 4 bytes

n!-0

Try it online.

Explanation:

   0 # Start with a(0)=0 (Oasis programs implicitly start with a(0)=1 unfortunately)
     # And calculate every following a(n) by:
  -  #  Subtracting
     #  the implicit previous term a(n-1)
n!   #  from n!
     # (and output the a(implicit input-argument)'th term implicitly as result)

Brachylog, 11 bytes

0|-₁↰I&ḟ;I-

Try it online!

Explanation

Uses the recurrence relation.

0             af(0) = 0
 |            Or
  -₁↰I        I = af(Input - 1)
      &ḟ;I-   Output = Input! - I

05AB1E, 4 bytes

L!®β

Port of @JonathanAllan's Jelly answer.

Try it online or verify all test cases.

Outputting the infinite sequence would be 5 bytes:

0λN!α

Try it online.

Explanation:

L     # Push a list in the range [1, (implicit) input-integer]
 !    # Get the factorial of each
  ®β  # Convert it from a base-(-1) list to a base-10 integer
      # (which is output implicitly as result)

 λ    # Start a recursive environment,
      # to output the infinite sequence
      # (which is output implicitly at the end)
0     # Start with a(0)=0
      # Where every other a(n) is calculated by:
      #  (implicitly push the previous term a(n-1)
    α #  Get the absolute difference between it
  N!  #  and n!

APL(Dyalog Unicode), 6 bytes SBCS

¯1⊥∘!⍳

Try it on APLgolf!

MATL, 7 bytes

:Yp-1ZQ

Try it online!

C (gcc), 32 bytes

f(n){n=n<2?n:n*f(n-2)+f(--n)*n;}

Try it online!

Port of Arnauld's JavaScript answer

Wolfram Language (Mathematica), 20 bytes

Nest[++i!-#&,i=0,#]&

Try it online!

Thunno 2, 6 bytes

RR€puḋ

(Thunno 2 isn't on ATO yet)

It seems that I forgot to add a "factorial" built-in to Thunno 2...

Port of Jonathan Allan's Jelly answer.

Explanation

RR€puḋ  # Implicit input                              5
R       # Push the range [1..input]                   [1, 2, 3, 4, 5]
 R      # For each number in this, push its range     [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
  €p    # Product of each inner list                  [1, 2, 6, 24, 120]
    uḋ  # Convert from base -1                        101
        # Implicit output

R, 29 31 bytes

Edit: +2 bytes and complete change of approach to fix bug spotted by pajonk

\(x)Reduce(`-`,gamma(x:1+1),,T)

Attempt This Online!

Japt, 4 bytes

õÊìJ

Try it

õÊìJ     :Implicit input of integer U
õ        :Range [1,U]
 Ê       :Factorials
  ì      :Convert from base
   J     :-1

><> (Fish), 53 42 bytes

i:?vl1=?n-30.
:?v\:1$:@*$1-
1.\6
00.\~~$1-

Try it

The bottom 3 lines calculate the factorial of a number and push it to the stack, the top line just subtracts the top 2 elements from the stack, and prints the top of the stack if there is just one.

After a number is printed, the - crashes and the program exits.

enter image description here

PARI/GP, 40 35 bytes

saved 5 bytes thanks to the comment.

Try it online!

f(n)=abs(sum(m=1,n,prod(k=1,m,-k)))

minigolf, 23 22 bytes

Ti,n;o,T*:1n,n*_*;+s,_

Attempt This Online!

Explanation

T            Push -1 (b)
i,n;         [1..n] range of input
o            Reverse it
,            Map in [n..1]:
  T*:          Multiply (b) by -1 (since -1^0 = 1
  1            Push 1
  n            Push curr. item
  ,n*_         Reduce 1..n by product
  *            mul. w/ b
;            End map
+            sum (works for 0 case since sum of [] is 0)
s,_          drop b

implicit output

Curry (PAKCS), 48 bytes

f 0=1
f x|x>0=x*f(x-1)
g 0=0
g x|x>0=f(x)-g(x-1)

Try it online!

My first answer in Curry. I had to determine the factorial because I couldn’t find it in the standard library

JavaScript (ES6), 28 bytes

f=n=>n<2?n:n*f(n-2)+--n*f(n)

Try it online!

This is based on the recurrence formula given on OEIS for \$n > 1\$:

$$a(n) = n\times a(n-2) + (n-1)\times a(n-1)$$

This alternate form accepts either Numbers or Bigints as input:

f=n=>n<2?n:n--*f(~-n)+n*f(n)

Try it online!

J, 10 bytes

_1#.1!@+i.

Port of Jonathan Allan's smart Jelly answer.

Attempt This Online!

_1#.1!@+i.
        i.  NB. range [0,n)
    1  +    NB. vectorized increment
     !@     NB. factorial of each
_1#.        NB. convert from base -1

Excel, 38 bytes

Defined Name a:

=LAMBDA(n,IF(n,FACT(n)-a(n-1),))

After which, within the worksheet:

=a(A1)

for an input in cell A1.

Python, 40 bytes

f=lambda n:n>1and~-n*f(n-1)+n*f(n-2)or n

Attempt This Online!

Port of @Arnauld's JS answer.

Desmos, 28 bytes

f(k)=∑_{n=1}^k(-1)^{k-n}n!

Try It On Desmos!

Yea, I really could not think of any golfier way than to just copy the formula provided in the question. Not the most creative answer out there but at least it's the golfiest in Desmos (at least it better be....).

Retina, 54 bytes

~(`.+
.+¶$$.($$'$&*
+`_(_(_+))
$$($.&$*$2$.1$*$1)
__
_

Try it online! Link includes test cases. Explanation: Port of @Arnauld's JavaScript answer.

~(`

Run the output of the rest of the program on the original input.

.+
.+¶$$.($$'$&*

Convert the input to unary and replace it with a command that replaces the input with an expression that converts the literal unary string back to decimal. The unary string represents f(n) at this point.

+`_(_(_+))
$$($.&$*$2$.1$*$1)

For n>2, repeatedly apply the recurrence relation f(n)=n*f(n-2)+(n-1)*f(n-1) to the unary string. n and (n-1) are represented in decimal while f(n-2) and f(n-1) remain represented in unary for the next pass.

__
_

f(2)=1 while f(n)=n for n<2 which is already correct.

Example: if n=7, then the rest of the program produces the following output:

.+
$.($'$(7*$(5*$(3*_2*_)4*$(4*_3*$(3*_2*_)))6*$(6*$(4*_3*$(3*_2*_))5*$(5*$(3*_2*_)4*$(4*_3*$(3*_2*_)))))

Retina will evaluate the expression using big integers so the limit is the length of the generated expression which has to fit in memory.

Note that there's an extra $' in the final expression in case it is empty to work around a Retina bug whereby $.() crashes Retina when it has no elements, but it's fine if it has a non-zero number of empty elements.

The recurrence relation is not used for f(2) because that would invoke f(0) whose representation would be empty, but * defaults to a RHS of _ i.e. 1. It could be done by representing f(n) with $(n) except that this triggers the empty length bug, so it needs another 3 bytes for a second copy of the workaround, making it overall a byte longer:

.+
.+¶$$.($$'$&*
~)+`_(_(_*))
$.&$*$$($$'$2)$.1$*$$($1)

Pyt, 10 bytes

řĐ1~⇹^⇹!·Å

Try it online!

ř                 implicit input (n); řangify [1,2,...,n]
 Đ                Đuplicate 
  1~              -1
    ⇹             swap top two elements
     ^            -1^[1,2,3,...,n]
      ⇹           swap top two elements
       !          factorial [1!,2!,3!,...,n!]
        ·         dot product
         Å        Åbsolute value; implicit print

Uses that fact that \$\text{af}(n)=\left|\sum_{i=1}^n(-1)^i i!\right|\$

Wolfram Language (Mathematica), 20 bytes

AlternatingFactorial

Try it online!

Charcoal, 12 bytes

I↨ENΠ…¹⁺²ι±¹

Attempt This Online! Link is to verbose version of code. Explanation:

   N            First input as a number
  E             Map over implicit range
     …          Range from
      ¹         Literal integer `1` to
         ι      Current value
       ⁺        Plus
        ²       Literal integer `2`
    Π           Take the product
 ↨        ±¹    Interpret as base `-1`
I               Cast to string
                Implicitly print

Jelly, 4 bytes

R!ḅ-

A monadic Link that accepts a non-negative integer, \$n\$, and yields its alternating factorial.

Try it online!

How?

R!ḅ- - Link: n
R    - range (n) -> [1, ..., n-1, n]
 !   - factorial -> [1!, ..., (n-1)!, n!]
   - - -1
  ḅ  - convert from base -1 -> n! - (n-1)! + ... [+/-] 1!

Vyxal, 4 bytes

ɾ¡uβ

Try it Online!

Port of the 4 byte jelly answer

Explained

ɾ¡uβ 
ɾ    # range [1, n]
 ¡   # factorial of each
  uβ # converted from base -1

Jelly, 6 bytes

R!_@ƒ0

Try it online!

How it works

R!_@ƒ0 - Main link. Takes n on the left
R      - Range; [1, 2, ..., n]
 !     - Factorial; [1, 2, 6, ..., n!]
    ƒ0 - Reduce by the following, beginning with 0:
  _@   -   y - x

For a list [a, b, c, d, e], _@ƒ0 calculates

((((0 _@ a) _@ b) _@ c) _@ d) _@ e
= e _ (d _ (c _ (b _ (a _ 0))))
= e - d + c - b + a - 0