Write a function that takes (x, y) and return x to the power of y WITHOUT Loops

APL (7)

{×/⍵/⍺}

Left argument is base, right argument is exponent, e.g.:

     5 {×/⍵/⍺} 6
15625

Explanation:

  • ⍵/⍺ replicates times, e.g. 5 {⍵/⍺} 6 -> 5 5 5 5 5 5
  • ×/ takes the product, e.g. ×/5 5 5 5 5 5 -> 5×5×5×5×5×5 -> 15625

C#: Floating point exponents

OK, this solution is quite fragile. You can easily break it by throwing ridiculously huge numbers like 6 at it. But it works beautifully for things like DoublePower(1.5, 3.4), and doesn't use recursion!

    static double IntPower(double x, int y)
    {
        return Enumerable.Repeat(x, y).Aggregate((product, next) => product * next);
    }

    static double Factorial(int x)
    {
        return Enumerable.Range(1, x).Aggregate<int, double>(1.0, (factorial, next) => factorial * next);
    }

    static double Exp(double x)
    {
        return Enumerable.Range(1, 100).
            Aggregate<int, double>(1.0, (sum, next) => sum + IntPower(x, next) / Factorial(next));
    }

    static double Log(double x)
    {
        if (x > -1.0 && x < 1.0)
        {
            return Enumerable.Range(1, 100).
                Aggregate<int, double>(0.0, (sum, next) =>
                    sum + ((next % 2 == 0 ? -1.0 : 1.0) / next * IntPower(x - 1.0, next)));
        }
        else
        {
            return Enumerable.Range(1, 100).
                Aggregate<int, double>(0.0, (sum, next) =>
                    sum + 1.0 / next * IntPower((x - 1) / x, next));
        }
    } 

    static double DoublePower(double x, double y)
    {
        return Exp(y * Log(x));
    } 

C++

How about some template meta programming? It bends what little rules there were, but it's worth a shot:

#include <iostream>


template <int pow>
class tmp_pow {
public:
    constexpr tmp_pow(float base) :
        value(base * tmp_pow<pow-1>(base).value)
    {
    }
    const float value;
};

template <>
class tmp_pow<0> {
public:
    constexpr tmp_pow(float base) :
        value(1)
    {
    }
    const float value;
};

int main(void)
{
    tmp_pow<5> power_thirst(2.0f);
    std::cout << power_thirst.value << std::endl;
    return 0;
}