# How to nest my own "times" function to get powers

I have a "times" function. I'd like to create a power function using it. It should look like this for an 6th power:

times[x, times[x, times[x, times[x, times[x, x]]]]]

I can't seem to figure out how to use Nest to get this. I'd like to create my power function to be something like p[x,n].

• I'm too lazy to write an answer, so: With[{n = 5}, (Composition @@ ConstantArray[times[x, #] &, n])[x]]. Jul 6, 2012 at 0:09

Nest[Times[#, x] &, x, 5]


or

Nest[# x &, x, 5]


or specifically for your times :

Nest[times[x, #] &, x, 5]

times[x, times[x, times[x, times[x, times[x, x]]]]]

• @MitchellKaplan I'm glad I could help. Jul 6, 2012 at 0:05
Fold[times[#2,#1]&,1,Table[x,{6}]]


This assumes your times function still leaves times[x,1] to be x.

• Nowadays, of course, one can do ConstantArray[x, 6] in place of Table[x, {6}]. Jul 5, 2012 at 23:59
• ah, sorry, I'm old school (have been hooked since v2.2, 1993). Jul 6, 2012 at 0:07
• No prob. I've been using it since version 2.2 also, and I still find myself slipping into old habits every so often... Jul 6, 2012 at 1:42

Assuming your "times" is associative, here's another more 'efficient' variation:

Clear[power];
power[b_, 1] := b;
power[b_, 0] := 1
power[b_, n_Integer] :=
With[{h = power[b, Quotient[n, 2]]}, b~times~h~times~h] /; Mod[n, 2] == 1;
power[b_, n_Integer] :=
With[{h = power[b, Quotient[n, 2]]}, h~times~h] /; Mod[n, 2] == 0;


This recursively splits the product into squares of half the power. In action:

power[x, 6]


times[times[times[x, x], x], times[times[x, x], x]]

Why might this be better? Consider:

times[a_, b_] := (count++; a b);

count = 0; {power[x, 250], count}
count = 0; {Nest[times[x, #] &, 1, 250], count}


{x^250, 12}

{x^250, 250}

times is only evaluated 12 times in this scheme compared to 250 times in the simple approach. For the same effort we could do:

count = 0; {power[x, 2^250], count}


{x^1809251394333065553493296640760748560207343510400633813116524750123\ 642650624, 250}

power[b_, n_] := b ~times~ power[b, n - 1]
power[b_, 0] := 1

power[x, 5]

times[x, times[x, times[x, times[x, times[x, 1]]]]]

• nice, +1 from me Jul 6, 2012 at 18:57

Just for variation and to add a little visual clue,

Attributes[Tpower] = {HoldFirst};
Tpower[x_^y_] := Fold[times[#2, #1] &, 1, ConstantArray[x, y]]


Gives:

Tpower[4^9]


times[4, times[4, times[4, times[4, times[4, times[4, times[4, times[4, times[4, 1]]]]]]]]]