(42S) Subfactorial
09-09-2021, 03:33 PM
Post: #8
 Albert Chan Senior Member Posts: 2,239 Joined: Jul 2018
RE: (42S) Subfactorial
(09-09-2021 07:24 AM)Werner Wrote:
(09-07-2021 02:21 PM)Albert Chan Wrote:
Code:
def subfac(n, r=0):     # integer n > 0     for i in range(2,n+1): r = 1-i*r     return abs(r)
Shouldn't that be
for i in range (2,n) ?

No, Python use 0-based indexing, open-intervals. To loop from 2 to n, we need range(2, n+1)

Mathematica have Subfactorial[n], but DIY is trivial, just nest (n+1) - 2 = n-1 times:

In[1]:= subfac[n_] := Nest[{1+First[#], 1-Times@@#}&, {2,0}, n-1] // Last // Abs

In[2]:= subfac[30]
Out[2]= 97581073836835777732377428235481

In[3]:= Round[30!/E]
Out[3]= 97581073836835777732377428235481
 « Next Oldest | Next Newest »

 Messages In This Thread (42S) Subfactorial - Eddie W. Shore - 09-06-2021, 04:43 PM RE: (42S) Subfactorial - John Keith - 09-06-2021, 06:50 PM RE: (42S) Subfactorial - Albert Chan - 09-07-2021, 02:21 PM RE: (42S) Subfactorial - Werner - 09-09-2021, 07:24 AM RE: (42S) Subfactorial - Albert Chan - 09-09-2021 03:33 PM RE: (42S) Subfactorial - Albert Chan - 09-08-2021, 10:26 PM RE: (42S) Subfactorial on HP-15C - C.Ret - 09-11-2021, 04:15 PM RE: (42S) Subfactorial - Werner - 09-09-2021, 07:45 AM RE: (42S) Subfactorial - Werner - 09-09-2021, 12:31 PM RE: (42S) Subfactorial - ijabbott - 09-11-2021, 08:24 AM RE: (42S) Subfactorial - Gil - 09-12-2021, 12:05 AM RE: (42S) Subfactorial - Albert Chan - 09-12-2021, 12:46 PM

User(s) browsing this thread: 1 Guest(s)