mardi 27 février 2018

How to count number of times recursion is called? (Computing number of multiplications for x^n)

I'm having some trouble figuring out how to increment count (mults in my code) in such a way that power2's counter is equivalent to power1's. My program compares the efficiency of computing x^n in different ways. I've looked up solutions on how to count the number of times a recursion calls itself but no matter what method I implement I get the incorrect output. Any help or guidelines would be appreciated!

This is part of my code so far (power1 has the right counter):

template <class T>
T power1(T x, unsigned int n, unsigned int& mults)
{
mults = 0;

if (n == 0)
    return 1;
else if (n == 1)
    return x;
else
{
    T total = 1;

    for (int i = 0; i < n; ++i)
    {
        total = total * x;
        ++mults;
    }
    mults -= 1;

    return total;
}
}


template <class T>
T power2(T x, unsigned int n, unsigned int& mults)
{
++mults;

if (n == 0)
{
    mults = 0;
    return 1;
}
else if (n == 1)
    return x;
else
{
    if (n > 1)
    {
        return (x * power2(x, n - 1, mults));
    }
}

return x;
}

This is part of my output:

Test for integer base:
2^0 = 1: mults1 = 0, mults2 = 0
2^1 = 2: mults1 = 0, mults2 = 1
2^2 = 4: mults1 = 1, mults2 = 3
2^3 = 8: mults1 = 2, mults2 = 6
2^4 = 16: mults1 = 3, mults2 = 10
2^5 = 32: mults1 = 4, mults2 = 15
2^6 = 64: mults1 = 5, mults2 = 21
2^7 = 128: mults1 = 6, mults2 = 28
2^8 = 256: mults1 = 7, mults2 = 36
2^9 = 512: mults1 = 8, mults2 = 45

Aucun commentaire:

Enregistrer un commentaire