| Bytes | Lang | Time | Link |
|---|---|---|---|
| 051 | Janet | 250507T204805Z | xigoi |
| 047 | Juby | 250507T184141Z | Jordan |
| 048 | Perl 5 MListUtil=product | 250507T201743Z | Xcali |
| 024 | CASIO BASIC CASIO fx9750GIII | 250507T190457Z | madeforl |
| 029 | x8664 machine code | 230711T172912Z | engineer |
| 031 | Haskell | 230422T155427Z | Wheat Wi |
| 012 | Pip | 230416T105644Z | The Thon |
| 023 | Julia 0.7 | 230420T184903Z | Kirill L |
| 049 | Zsh | 230420T022835Z | GammaFun |
| 025 | Raku | 230420T003439Z | Jo King |
| 005 | Pyth | 230419T152054Z | CursorCo |
| 054 | Rust | 230418T145629Z | JSorngar |
| 015 | Ohm v2 | 230417T231333Z | Cliff |
| 039 | FunStack alpha | 230417T214107Z | DLosc |
| 064 | BrainFlak | 230417T200428Z | Nitrodon |
| 510 | Nibbles | 230416T175152Z | Dominic |
| 004 | Oasis | 230417T085421Z | Kevin Cr |
| 011 | Brachylog | 230417T091714Z | Fatalize |
| 004 | 05AB1E | 230417T083553Z | Kevin Cr |
| 006 | APLDyalog Unicode | 230416T195930Z | user1172 |
| 007 | MATL | 230416T195337Z | beaker |
| 032 | C gcc | 230416T181158Z | Noodle9 |
| 020 | Wolfram Language Mathematica | 230416T171750Z | att |
| 006 | Thunno 2 | 230416T104938Z | The Thon |
| 031 | R | 230416T080743Z | Dominic |
| 004 | Japt | 230416T115536Z | Shaggy |
| 5342 | ><> Fish | 230416T065608Z | mousetai |
| 4035 | PARI/GP | 230416T011001Z | 138 Aspe |
| 022 | minigolf | 230416T003327Z | user1176 |
| 048 | Curry PAKCS | 230416T090911Z | lesobrod |
| 028 | JavaScript ES6 | 230415T223202Z | Arnauld |
| 010 | J | 230416T081323Z | south |
| 038 | Excel | 230416T051914Z | Jos Wool |
| 040 | Python | 230416T031658Z | loopy wa |
| 028 | Desmos | 230416T020210Z | Aiden Ch |
| 054 | Retina | 230416T010747Z | Neil |
| 010 | Pyt | 230415T235504Z | Kip the |
| 020 | Wolfram Language Mathematica | 230415T233946Z | Unmitiga |
| 012 | Charcoal | 230415T232725Z | Neil |
| 004 | Jelly | 230415T223744Z | Jonathan |
| 004 | Vyxal | 230415T224135Z | lyxal |
| 006 | Jelly | 230415T222758Z | caird co |
Janet, 51 bytes
|(reduce|(-(*;(map|(+ $ 2)(range $1)))$)0(range $))
J-uby, 47 bytes
:+|:*&(:+|:/&:*)|:~|~:zip&[1,-1].cycle|:sum++:*
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..$_
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
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
Pip, 17 16 12 bytes
$* *\,\,aFDv
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
Zsh, 49 bytes
r=i=$[$1>0]
for n ({$1..2})((r=r*n+(i=-i)))
<<<$r
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..$_}
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 $_-=$*=++$}...*)[$_]}
If this IO method ends up allowed as default, then this can be shortened to 23 bytes.
Pyth, 5 bytes
aF.!S
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!
Ohm v2, 15 bytes
?@(!1→ρΓ³#R(ⁿ*Σ
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
{(({})[()]<({([{}]()({}))([{}]({}))}{}{}([{}])((){}))>)}{}({}<>)
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
/.\,$`*,$-
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
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-
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!α
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!
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)
Japt, 4 bytes
õÊìJ
õÊì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-
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.
minigolf, 23 22 bytes
Ti,n;o,T*:1n,n*_*;+s,_
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)
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)
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)
J, 10 bytes
_1#.1!@+i.
Port of Jonathan Allan's smart Jelly answer.
_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.
Desmos, 28 bytes
f(k)=∑_{n=1}^k(-1)^{k-n}n!
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~⇹^⇹!·Å
ř 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|\$
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.
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β
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
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
