15
\$\begingroup\$

This is a really neat short challenge.

Write a function or a procedure that takes two parameters, x and y and returns the result of xy WITHOUT using loops, or built in power functions.

The winner is the most creative solution, and will be chosen based on the highest number of votes after 3 days.

\$\endgroup\$
13
  • 1
    \$\begingroup\$ What sort of challenge is this? \$\endgroup\$
    – VisioN
    Commented Mar 5, 2014 at 12:01
  • 22
    \$\begingroup\$ How about exp(log(x)*y)? \$\endgroup\$
    – r3mainer
    Commented Mar 5, 2014 at 12:04
  • 2
    \$\begingroup\$ Is an answer for integers only acceptable? Since these are the first replies. \$\endgroup\$
    – mmumboss
    Commented Mar 5, 2014 at 12:59
  • 4
    \$\begingroup\$ Looks like the answers so far either use recursion or lists of repeated 'x's. I'm wracking my brains trying to think of another way (particularly something that allows a non-integer y). \$\endgroup\$
    – BenM
    Commented Mar 5, 2014 at 16:47
  • 1
    \$\begingroup\$ Unfortunately the prohibition on loops rules out fun mathematical solutions like Taylor expansion. \$\endgroup\$ Commented Jul 31, 2014 at 3:15

57 Answers 57

27
\$\begingroup\$

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
\$\endgroup\$
4
  • 2
    \$\begingroup\$ Hm.. This can be written in 5 characters in J, exactly the same method. */@$~ \$\endgroup\$
    – seequ
    Commented Jul 30, 2014 at 18:32
  • \$\begingroup\$ @Sieg 4 even, if you allow exponent on the left, base on the right. \$\endgroup\$ Commented Feb 20, 2015 at 17:16
  • \$\begingroup\$ I had the flip adverb because I thought it's not allowed. \$\endgroup\$
    – seequ
    Commented Feb 20, 2015 at 18:44
  • \$\begingroup\$ @Seeq 4 in Dyalog APL: ×/⍴⍨ \$\endgroup\$
    – Adám
    Commented Jun 16, 2016 at 23:30
27
\$\begingroup\$

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));
    } 
\$\endgroup\$
2
  • 43
    \$\begingroup\$ "ridiculously huge numbers like 6" I enjoyed that. \$\endgroup\$
    – DavidC
    Commented Mar 5, 2014 at 21:59
  • \$\begingroup\$ Surely use of Enumerable functions is relying on looping that was forbidden in the question or is it ok because the loop is inside framework methods? \$\endgroup\$
    – Chris
    Commented Mar 7, 2014 at 9:42
15
\$\begingroup\$

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;
}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ but this isn't a function, is a compile-time value, isn't it? :O \$\endgroup\$ Commented Mar 6, 2014 at 8:49
  • \$\begingroup\$ Well, a constructor is a function, and template parameters are almost like function arguments... right? =) \$\endgroup\$
    – erlc
    Commented Mar 7, 2014 at 13:47
  • \$\begingroup\$ @PaperBirdMaster Yeah... that's why I admitted to some rule bending. I thought I was going to submit something besides tail-recursion, but I just submitted compile time tail recursion, haha. Close enough though, right? \$\endgroup\$
    – astephens4
    Commented Mar 7, 2014 at 16:19
  • \$\begingroup\$ @astephens4 close enough, I love it :3 \$\endgroup\$ Commented Mar 7, 2014 at 23:46
15
\$\begingroup\$

Python

def power(x,y):
    return eval(((str(x)+"*")*y)[:-1])

Doesn't work for noninteger powers.

\$\endgroup\$
6
  • \$\begingroup\$ I like this one. \$\endgroup\$ Commented Mar 5, 2014 at 20:06
  • 1
    \$\begingroup\$ Why are you adding a separator without using join? eval('*'.join([str(x)] * y)). \$\endgroup\$
    – Bakuriu
    Commented Mar 6, 2014 at 7:45
  • 1
    \$\begingroup\$ Was this code-trolling? \$\endgroup\$
    – gerrit
    Commented Mar 6, 2014 at 14:51
  • \$\begingroup\$ Would like to also note that python has the ** operator, so you could've eval()d that. \$\endgroup\$
    – Riking
    Commented Mar 6, 2014 at 21:14
  • 3
    \$\begingroup\$ @Riking: that'd be an inbuilt, though. \$\endgroup\$
    – Hovercouch
    Commented Mar 6, 2014 at 21:50
10
\$\begingroup\$

Haskell - 25 chars

f _ 0=1
f x y=x*f x (y-1)

Following Marinus' APL version:

f x y = product $ take y $ repeat x

With mniip's comment and whitespace removed, 27 chars:

f x y=product$replicate y x
\$\endgroup\$
3
  • \$\begingroup\$ use replicate y x instead of take y $ repeat x \$\endgroup\$
    – mniip
    Commented Mar 5, 2014 at 18:38
  • 4
    \$\begingroup\$ I was convinced that you could save characters by writing your second function pointfree. As it turns out f=(product.).flip replicate is exactly the same number of chars. \$\endgroup\$
    – Kaya
    Commented Mar 6, 2014 at 2:17
  • \$\begingroup\$ @mniip It doesn't matter, this isn't code golf. \$\endgroup\$
    – user344
    Commented Dec 10, 2014 at 14:44
10
\$\begingroup\$

Python

If y is a positive integer

def P(x,y):
    return reduce(lambda a,b:a*b,[x]*y)
\$\endgroup\$
0
7
\$\begingroup\$

JavaScript (ES6), 31

// Testable in Firefox 28
f=(x,y)=>eval('x*'.repeat(y)+1)

Usage:

> f(2, 0)
1
> f(2, 16)
65536

Explanation:

The above function builds an expression which multiply x y times then evaluates it.

\$\endgroup\$
6
\$\begingroup\$

I'm surprised to see that nobody wrote a solution with the Y Combinator, yet... thus:

Python2

Y = lambda f: (lambda x: x(x))(lambda y: f(lambda v: y(y)(v)))
pow = Y(lambda r: lambda (n,c): 1 if not c else n*r((n, c-1)))

No loops, No vector/list operations and No (explicit) recursion!

>>> pow((2,0))
1
>>> pow((2,3))
8
>>> pow((3,3))
27
\$\endgroup\$
1
  • \$\begingroup\$ Uh, I've just seen right now KChaloux's Haskell solution that uses fix, upvoting him... \$\endgroup\$
    – berdario
    Commented Mar 6, 2014 at 16:35
5
\$\begingroup\$

C# : 45

Works for integers only:

int P(int x,int y){return y==1?x:x*P(x,y-1);}
\$\endgroup\$
5
  • \$\begingroup\$ Beat me to it :-) I think you could save a few bytes by writing return --y?x:x*P(x,y); instead \$\endgroup\$
    – r3mainer
    Commented Mar 5, 2014 at 12:13
  • 1
    \$\begingroup\$ But this isn't code-golf... \$\endgroup\$
    – Oberon
    Commented Mar 5, 2014 at 12:26
  • 1
    \$\begingroup\$ @oberon winning criteria was not clear when this was posted. Things have moved on. \$\endgroup\$ Commented Mar 5, 2014 at 13:47
  • \$\begingroup\$ @steveverrill Sorry. \$\endgroup\$
    – Oberon
    Commented Mar 5, 2014 at 13:54
  • \$\begingroup\$ Also in C# --y would be an int which is not the same as a bool like in other languages. \$\endgroup\$
    – Chris
    Commented Mar 7, 2014 at 9:39
5
\$\begingroup\$

bash & sed

No numbers, no loops, just an embarrasingly dangerous glob abuse. Preferably run in an empty directory to be safe. Shell script:

#!/bin/bash
rm -f xxxxx*
eval touch $(printf xxxxx%$2s | sed "s/ /{1..$1}/g")
ls xxxxx* | wc -l
rm -f xxxxx*
\$\endgroup\$
1
  • \$\begingroup\$ "Preferably run in an empty directory to be safe." :D \$\endgroup\$
    – Almo
    Commented Mar 6, 2014 at 13:53
5
\$\begingroup\$

Javascript

function f(x,y){return ("1"+Array(y+1)).match(/[\,1]/g).reduce(function(l,c){return l*x;});}

Uses regular expressions to create an array of size y+1 whose first element is 1. Then, reduce the array with multiplication to compute power. When y=0, the result is the first element of the array, which is 1.

Admittedly, my goal was i) not use recursion, ii) make it obscure.

\$\endgroup\$
5
\$\begingroup\$

Mathematica

f[x_, y_] := Root[x, 1/y]

Probably cheating to use the fact that x^(1/y) = y√x

\$\endgroup\$
2
  • \$\begingroup\$ Not cheating. Smart. \$\endgroup\$ Commented Mar 12, 2014 at 21:49
  • \$\begingroup\$ This is brilliant. Wish I'd thought of it for my R post. \$\endgroup\$ Commented Jul 31, 2014 at 4:47
4
\$\begingroup\$

Golfscript, 8 characters (including I/O)

~])*{*}*

Explanation:

TLDR: another "product of repeated array" solution.

The expected input is two numbers, e.g. 2 5. The stack starts with one item, the string "2 5".

Code     - Explanation                                             - stack
                                                                   - "2 5"
~        - pop "2 5" and eval into the integers 2 5                - 2 5        
]        - put all elements on stack into an array                 - [2 5]
)        - uncons from the right                                   - [2] 5
*        - repeat array                                            - [2 2 2 2 2]
{*}      - create a block that multiplies two elements             - [2 2 2 2 2] {*}
*        - fold the array using the block                          - 32
\$\endgroup\$
1
  • \$\begingroup\$ Golfscript is always the way to go. \$\endgroup\$
    – Etheryte
    Commented Mar 7, 2014 at 0:27
3
\$\begingroup\$

Ruby

class Symbol
  define_method(:**) {|x| eval x }
end

p(:****[$*[0]].*(:****$*[1]).*('*'))

Sample use:

$ ruby exp.rb 5 3
125
$ ruby exp.rb 0.5 3
0.125

This ultimately is the same as several previous answers: creates a y-length array every element of which is x, then takes the product. It's just gratuitously obfuscated to make it look like it's using the forbidden ** operator.

\$\endgroup\$
3
\$\begingroup\$

JavaScript

function f(x,y){return y--?x*f(x,y):1;}
\$\endgroup\$
0
3
\$\begingroup\$

C, exponentiation by squaring

int power(int a, int b){
    if (b==0) return 1;
    if (b==1) return a;
    if (b%2==0) return power (a*a,b/2);
    return a*power(a*a,(b-1)/2);
}

golfed version in 46 bytes (thanks ugoren!)

p(a,b){return b<2?b?a:1:p(a*a,b/2)*(b&1?a:1);}

should be faster than all the other recursive answers so far o.O

slightly slower version in 45 bytes

p(a,b){return b<2?b?a:1:p(a*a,b/2)*p(a,b&1);}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ For odd b, ~-b/2 == b/2. \$\endgroup\$
    – ugoren
    Commented Mar 5, 2014 at 17:49
  • \$\begingroup\$ @ugoren oh sure, you're right \$\endgroup\$
    – izabera
    Commented Mar 5, 2014 at 18:31
  • \$\begingroup\$ This is a popular interview question :) "How can you write pow(n, x) better than O(n)?" \$\endgroup\$ Commented Mar 6, 2014 at 0:28
3
\$\begingroup\$

Haskell - 55

pow x y=fix(\r a i->if i>=y then a else r(a*x)(i+1))1 0

There's already a shorter Haskell entry, but I thought it would be interesting to write one that takes advantage of the fix function, as defined in Data.Function. Used as follows (in the Repl for the sake of ease):

ghci> let pow x y=fix(\r a i->if i>=y then a else r(a*x)(i+1))1 0
ghci> pow 5 3
125
\$\endgroup\$
0
2
\$\begingroup\$

Q

9 chars. Generates array with y instances of x and takes the product.

{prd y#x}

Can explicitly cast to float for larger range given int/long x:

{prd y#9h$x}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Matching Golfscript in length is a feat to achieve. \$\endgroup\$
    – Etheryte
    Commented Mar 7, 2014 at 0:29
2
\$\begingroup\$

Similar logic as many others, in PHP:

<?=array_product(array_fill(0,$argv[2],$argv[1]));

Run it with php file.php 5 3 to get 5^3

\$\endgroup\$
2
\$\begingroup\$

I'm not sure how many upvotes I can expect for this, but I found it somewhat peculiar that I actually had to write that very function today. And I'm pretty sure this is the first time any .SE site sees this language (website doesn't seem very helpful atm).

ABS

def Rat pow(Rat x, Int y) =
    if y < 0 then
        1 / pow(x, -y)
    else case y {
        0 => 1;
        _ => x * pow(x, y-1);
    };

Works for negative exponents and rational bases.

I highlighted it in Java syntax, because that's what I'm currently doing when I'm working with this language. Looks alright.

\$\endgroup\$
0
2
\$\begingroup\$

Pascal

The challenge did not specify the type or range of x and y, therefore I figure the following Pascal function follows all the given rules:

{ data type for a single bit: can only be 0 or 1 }
type
  bit = 0..1;

{ calculate the power of two bits, using the convention that 0^0 = 1 }
function bitpower(bit x, bit y): bit;
  begin
    if y = 0
      then bitpower := 1
      else bitpower := x
  end;

No loop, no built-in power or exponentiation function, not even recursion or arithmetics!

\$\endgroup\$
2
\$\begingroup\$

J - 5 or 4 bytes

Exactly the same as marinus' APL answer.

For x^y:

*/@$~

For y^x:

*/@$

For example:

   5 */@$~ 6
15625
   6 */@$ 5
15625

x $~ y creates a list of x repeated y times (same as y $ x

*/ x is the product function, */ 1 2 3 -> 1 * 2 * 3

\$\endgroup\$
1
\$\begingroup\$

Python

from math import sqrt

def pow(x, y):
    if y == 0:
        return 1
    elif y >= 1:
        return x * pow(x, y - 1)
    elif y > 0:
        y *= 2
        if y >= 1:
            return sqrt(x) * sqrt(pow(x, y % 1))
        else:
            return sqrt(pow(x, y % 1))
    else:
        return 1.0 / pow(x, -y)
\$\endgroup\$
4
  • 1
    \$\begingroup\$ ** is built-in operator imo. \$\endgroup\$ Commented Mar 5, 2014 at 12:28
  • \$\begingroup\$ @SilviuBurcea True, editing. \$\endgroup\$
    – Oberon
    Commented Mar 5, 2014 at 12:30
  • \$\begingroup\$ @SilviuBurcea operator =/= function \$\endgroup\$
    – VisioN
    Commented Mar 5, 2014 at 12:32
  • \$\begingroup\$ @VisioN true, but the idea was about built-ins. I don't think the OP knows about all these built-in operators ... \$\endgroup\$ Commented Mar 5, 2014 at 12:34
1
\$\begingroup\$

Javascript

With tail recursion, works if y is a positive integer

function P(x,y,z){z=z||1;return y?P(x,y-1,x*z):z}
\$\endgroup\$
0
1
\$\begingroup\$

Bash

Everyone knows bash can do whizzy map-reduce type stuff ;-)

#!/bin/bash

x=$1
reduce () {
    ((a*=$x))
}
a=1
mapfile -n$2 -c1 -Creduce < <(yes)
echo $a

If thats too trolly for you then there's this:

#!/bin/bash

echo $(( $( yes $1 | head -n$2 | paste -s -d'*' ) ))
\$\endgroup\$
1
\$\begingroup\$

C

Yet another recursive exponentiation by squaring answer in C, but they do differ (this uses a shift instead of division, is slightly shorter and recurses one more time than the other):

e(x,y){return y?(y&1?x:1)*e(x*x,y>>1):1;}
\$\endgroup\$
1
\$\begingroup\$

Mathematica

This works for integers.

f[x_, y_] := Times@@Table[x, {y}]

Example

f[5,3]

125


How it works

Table makes a list of y x's. Times takes the product of all of them.`


Another way to achieve the same end:

#~Product~{i,1,#2}&

Example

#~Product~{i, 1, #2} & @@ {5, 3}

125

\$\endgroup\$
1
\$\begingroup\$

Windows Batch

Like most of the other answers here, it uses recursion.

@echo off
set y=%2
:p
if %y%==1 (
set z=%1
goto :eof
) else (
    set/a"y-=1"
    call :p %1
    set/a"z*=%1"
    goto :eof
)

x^y is stored in the environment variable z.

\$\endgroup\$
1
\$\begingroup\$

perl

Here's a tail recursive perl entry. Usage is echo $X,$Y | foo.pl:

($x,$y) = split/,/, <>;
sub a{$_*=$x;--$y?a():$_}
$_=1;
print a

Or for a more functional-type approach, how about:

($x,$y) = split/,/, <>;
$t=1; map { $t *= $x } (1..$y);
print $t
\$\endgroup\$
2
  • \$\begingroup\$ "a: stuff goto a if something" looks like a loop. \$\endgroup\$ Commented Mar 6, 2014 at 1:34
  • \$\begingroup\$ Yep, the goto version is a loop, but isn't tail recursion also essentially a loop? \$\endgroup\$ Commented Mar 6, 2014 at 2:21
1
\$\begingroup\$

Python

def getRootOfY(x,y):
   return x**y 

def printAnswer():
   print "answer is ",getRootOfY(5,3)
printAnswer()

answer =125

I am not sure if this is against the requirements, but if not here is my attempt.

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG! When you do your language header you can leave out the "language=" since by custom everyone puts the language in the header so that's understood. You may indeed have run afoul of the rules here, but we'll let the voters decide. Glad to have a new member at the country club. \$\endgroup\$ Commented Mar 6, 2014 at 4:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.