Find subfactorial of a number

Given an integer N, the task is to find the subfactorial of the number represented as !N. The subfactorial of a number is defined using below recurrence relation of a number N:!N = (N-1) [ !(N-2) + !(N-1) ]where !1 = 0 and !0 = 1Some of the subfactorials are:n012345678910111213!n10129442651, 85414, 833133, 4961, 334, 96114, 684, 570176, 214, 8412, 290, 792, 932Examples:Input: N = 4Output: 9Explanation: !4 = !(4-1)*4 + (-1)4 = !3*4 + 1!3 = !(3 – 1)*3 + (-1)3 = !2*3 – 1!2 = !(2 – 1)*2 + (-1)2 = !1*2 + 1!1 = !(1 – 1)*1 + (-1)1 = !0*1 – 1Since !0 = 1, therefore !1 = 0, !2 = 1, !3 = 2 and !4 = 9. Input: N = 0Output: 1Approach: The subfactorial of the number N can also be calculated as: 0.end{cases}}}” title=”Rendered by QuickLaTeX.com” height=”79″ width=”428″/>Expanding this gives => !N = ( N! )*( 1 – 1/(1!) + (1/2!) – (1/3!)  …….. (1/N!)*(-1)N )Therefore the above series can be used to find the subfactorial of number N. Follow the steps below to see how:Initialize variables, say res = 0, fact = 1 and count = 0.Iterate over the range from 1 to N using i and do the following:Update fact as fact*i.If the count is even then update res as res = res – (1 / fact).If the count is odd then update res as res = res + (1 / fact).Increase the value of count by 1.Finally, return fact*(1 + res).Below is the implementation of the above approach:C++#include using namespace std;  double subfactorial(int N){          double res = 0, fact = 1;    int count = 0;          for (int i = 1; i