user11416547
user11416547

Reputation:

Recursion equivalent of a iterative version for calculating series tip from where to start ( Homework )

I have the following serie N[i] = n[i - 1] + 2 * [n-2] - 3 * [n - 3] wheni > 3; So the first elements are n1 = 5/2; n2 = 3; n3 = 4; I must make a function to give back the n-th member. I have created a iterative version but i cannot figure out from where to start to make a recursive version of it. If someone can give me a tip from where to start. I have basic understanding how recursion works but i know simple problems like Fibonacci and factorials etc. that are very easy. Can someone give me a tip from where to start ? Here is the iterative version of the problem.

namespace Series
{
    class Program
    {
        static void Main(string[] args)
        {
            double ans = func(7);
            Console.WriteLine("ans " + ans);
            Console.ReadLine();
        }

        static double func(int n)
        {
            double[] arr = new double[n + 1];
            double ans = 0;
            double x = 5.0;
            double y = 2.0;
            arr[0] = x / y;
            arr[1] = 3.0;
            arr[2] = 4.0;

            for (int i = 3; i < arr.GetLength(0); i++)
            {
                double val = arr[i - 1] + 2 * (arr[i - 2]) - 3 * (arr[i - 3]);
                arr[i] = val;
            }
            printArr(arr);
            return arr[i + 1];
        }

        static void printArr(double[] arr)
        {
            for (int i = 0; i < arr.GetLength(0); i++)
                Console.Write(arr[i] + " ");

            Console.WriteLine();
        }
    }
} 

Upvotes: 0

Views: 52

Answers (1)

user11523568
user11523568

Reputation:

You should add edge cases first, then use recursion to let induction take place.

static double func(int n)
{
    // if (n < 0) // <- whatever needs to happen here?
    if (n == 0) return 2.5;
    if (n == 1) return 3;
    if (n == 2) return 4;
    return func(n - 1) + func(n - 2) * 2 - func(n - 3) * 3;
} 

This is a naive approach. You can start with this and see if you can implement some caching.

Upvotes: 1

Related Questions