jeudi 24 septembre 2020

C++ algorithm code for Magical sequence that will generate desired output

The Magical Sequence

A Magical Sequence is defined as shown.

Magical[1] = 0
Magical[2] = 1
Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + n*1, for n > 2

Given n (1 <= n <= 10^9 ), find Magical[n].

Example 1: input: 3 Output: 4

Explanation:

Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + 3*1
    Magical[3] = 1*Magical[2] + 2*Magical[1] + 3*1
    Magical[3] = 1*1 + 2*0 + 3*1
    Magical[3] = 4

Example 2: input: 4 Output: 10

Magical[4] = 1*Magical[3]+2*Magical[2]+3*Magical[1]+4*1
          = 1*4+2*1+3*0+4 = 10

Example 3: input: 5 Output: 26

Magical[5] = 1*Magical[4]+2*Magical[3]+3*Magical[2]+4*Magical[1]+5*1
          = 1*10+2*4+3*1+4*0+5 = 26

I tried something like below :-

int CuckooNum(int n)
{
    if (1 == n)
    {
        return 0;
    }
    else if (2 == n)
    {
        return 1;
    }

    std::vector<int> vec;
    vec.resize(n);
    vec[0] = 4;
    vec[1] = 0;
    vec[2] = 1;

    int multiplyer = n;
    int result = 0;
    for (int index=3; index <= n; index++)
    {
        result += multiplyer * vec[index-1];
        vec[index] = result;
        multiplyer--;
    }
    return result;
}

Aucun commentaire:

Enregistrer un commentaire