Question:
How to calculate recursive sequence using C++

Summary

Here we have to define a class ‘Solution’ with a member function ‘sequence (int n)’ that calculates a sequence based on the input parameter ‘n’. 


Solution

//User function Template for C++


class Solution{

public:

        int mod=1e9+7;

        long long ans = 0;

        void solve(int n, int ind, int m){

            if(ind > n){

                return;

            }

            

            long long result = 1;

            for(int i=0; i < ind; i++){

                result = (result*m)%mod;

                m++;

            }

            ans+=result;

            solve(n, ind+1, m); 

        } 

    long long sequence(int n){

        // code here

        

        solve(n,1,1);

        // int trk = 1;

        // for(int i=1; i<=n; i++){

        //     ans += ans;

        //     for(int j=1; j<=i; j++){

        //         ans = ans*trk;

        //         trk++;

        //     }

        // }

        return ans%mod;;

    }

};


Explanation

Public Member Functions

  • This function calculates the sequence for the given value of n.


Modulus Constant

  • This line defines a constant mod with a value of

109+7

10

9

  • +7. This is often used in competitive programming to perform modulo arithmetic to avoid integer overflow.


Private Member Variable

  • This variable ans is initialized to 0. It will accumulate the result of the sequence calculation.


Recursive Function

  • n: The total number of elements in the sequence.

  • ind: The current index in the sequence.

  • m: A multiplier used in the calculation.



Suggested blogs:

>Find the number of pairs of elements whose sum is equal to K using C++

>How to check whether string is palindrome or not using C++

>How to determine the smallest possible size of a vertex cover using C++

>Build an Electron application from scratch

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)


Nisha Patel

Nisha Patel

Submit
0 Answers