Knuth's power tree: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Wren}}: Minor tidy) |
|||
(24 intermediate revisions by 12 users not shown) | |||
Line 1:
{{task|Knuth's power tree}}
(Knuth's power tree is used for computing <big><big>x<sup>n</sup></big></big> efficiently
;Task:
Compute and show the list of Knuth's power tree integers necessary for the computation of:
Line 12 ⟶ 11:
Then, using those integers, calculate and show the exact
::* <big>2<sup>n</sup></big> where n ranges from 0 ──► 17 (inclusive) <br>
Line 19 ⟶ 18:
A ''zero'' power is often handled separately as a special case.
Optionally, support negative integer powers.
;Example:
An example of a small power tree for some low integers:
<pre>
1
\
2
___________________________________________/ \
/ \
3 4
/ \____________________________________ \
/ \ \
5 6 8
/ \____________ / \ \
/ \ / \ \
7 10 9 12 16
/ //\\ │ │ /\
/ _____// \\________ │ │ / \
14 / / \ \ │ │ / \
/│ \ 11 13 15 20 18 24 17 32
/ │ \ │ /\ /\ │ /\ │ /\ │
/ │ \ │ / \ / \ │ / \ │ / \ │
38 35 42 29 31 56 44 46 39 52 50 45 60 41 43 80 54 37 72 49 51 96 66 68 65 128
</pre>
Where, for the power <big>43</big>, following the tree "downwards" from <big>1</big>:
Line 74 ⟶ 72:
<br>
;References:
::* Donald E. Knuth's book: ''The Art of Computer Programming, Vol. 2'', Second Edition, Seminumerical Algorithms, section 4.6.3: Evaluation of Powers.
::* link [http://codegolf.stackexchange.com/questions/3177/knuths-power-tree codegolf.stackexchange.com/questions/3177/knuths-power-tree] It shows a '''Haskell''', '''Python''', and a '''Ruby''' computer program example (but they are mostly ''code golf'').
::* link [https://comeoncodeon.wordpress.com/tag/knuth/ comeoncodeon.wordpress.com/tag/knuth/] (See the section on Knuth's Power Tree.) It shows a '''C++''' computer program example.
::* link to Rosetta Code [http://rosettacode.org/wiki/Addition-chain_exponentiation addition-chain exponentiation].
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V p = [1 = 0]
V lvl = [[1]]
F path(n)
I !n
R [Int]()
L n !C :p
[Int] q
L(x) :lvl[0]
L(y) path(x)
I !(x + y C :p)
:p[x + y] = x
q.append(x + y)
:lvl[0] = q
R path(:p[n]) [+] [n]
F tree_pow(x, n)
T Ty = T(x)
V (r, p) = ([0 = Ty(1), 1 = x], 0)
L(i) path(n)
r[i] = r[i - p] * r[p]
p = i
R r[n]
F show_pow_i(x, n)
print("#.: #.\n#.^#. = #.\n".format(n, path(n), x, n, tree_pow(BigInt(x), n)))
F show_pow_f(x, n)
print("#.: #.\n#.^#. = #.6\n".format(n, path(n), x, n, tree_pow(x, n)))
L(x) 18
show_pow_i(2, x)
show_pow_i(3, 191)
show_pow_f(1.1, 81)</syntaxhighlight>
{{out}}
<pre>
0: []
2^0 = 1
1: [1]
2^1 = 2
2: [1, 2]
2^2 = 4
3: [1, 2, 3]
2^3 = 8
4: [1, 2, 4]
2^4 = 16
5: [1, 2, 3, 5]
2^5 = 32
6: [1, 2, 3, 6]
2^6 = 64
7: [1, 2, 3, 5, 7]
2^7 = 128
8: [1, 2, 4, 8]
2^8 = 256
9: [1, 2, 3, 6, 9]
2^9 = 512
10: [1, 2, 3, 5, 10]
2^10 = 1024
11: [1, 2, 3, 5, 10, 11]
2^11 = 2048
12: [1, 2, 3, 6, 12]
2^12 = 4096
13: [1, 2, 3, 5, 10, 13]
2^13 = 8192
14: [1, 2, 3, 5, 7, 14]
2^14 = 16384
15: [1, 2, 3, 5, 10, 15]
2^15 = 32768
16: [1, 2, 4, 8, 16]
2^16 = 65536
17: [1, 2, 4, 8, 16, 17]
2^17 = 131072
191: [1, 2, 3, 5, 7, 14, 19, 38, 57, 95, 190, 191]
3^191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
81: [1, 2, 3, 5, 10, 20, 40, 41, 81]
1.1^81 = 2253.240236
</pre>
=={{header|Ada}}==
In this program the power tree is in a generic package which is instantiated for each base value.
<syntaxhighlight lang="ada">with Ada.Containers.Ordered_Maps;
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Text_IO; use Ada.Text_IO;
procedure Power_Tree is
Debug_On : constant Boolean := False;
generic
type Result_Type is private;
Base : Result_Type;
Identity : Result_Type;
with function "*" (Left, Right : Result_Type) return Result_Type is <>;
package Knuth_Power_Tree is
subtype Exponent is Natural;
function Power (Exp : Exponent) return Result_Type;
end Knuth_Power_Tree;
package body Knuth_Power_Tree is
package Power_Trees is
new Ada.Containers.Ordered_Maps (Key_Type => Exponent,
Element_Type => Result_Type);
Tree : Power_Trees.Map;
procedure Debug (Item : String) is
begin
if Debug_On then
Put_Line (Standard_Error, Item);
end if;
end Debug;
function Power (Exp : Exponent) return Result_Type is
Pow : Result_Type;
begin
if Tree.Contains (Exp) then
return Tree.Element (Exp);
else
Debug ("lookup failed of " & Exp'Image);
end if;
if Exp mod 2 = 0 then
Debug ("lookup half " & Exponent'(Exp / 2)'Image);
Pow := Power (Exp / 2);
Pow := Pow * Pow;
else
Debug ("lookup one less " & Exponent'(Exp - 1)'Image);
Pow := Power (Exp - 1);
Pow := Result_Type (Base) * Pow;
end if;
Debug ("insert " & Exp'Image);
Tree.Insert (Key => Exp, New_Item => Pow);
return Pow;
end Power;
begin
Tree.Insert (Key => 0, New_Item => Identity);
end Knuth_Power_Tree;
procedure Part_1
is
package Power_2 is new Knuth_Power_Tree (Result_Type => Long_Integer,
Base => 2,
Identity => 1);
R : Long_Integer;
begin
Put_Line ("=== Part 1 ===");
for N in 0 .. 25 loop
R := Power_2.Power (N);
Put ("2 **"); Put (N'Image);
Put (" ="); Put (R'Image);
New_Line;
end loop;
end Part_1;
procedure Part_2
is
use Ada.Numerics.Big_Numbers.Big_Integers;
package Power_3 is new Knuth_Power_Tree (Result_Type => Big_Integer,
Base => 3,
Identity => 1);
R : Big_Integer;
begin
Put_Line ("=== Part 2 ===");
for E in 190 .. 192 loop
R := Power_3.Power (E);
Put ("3 **" & E'Image & " ="); Put (R'Image); New_Line;
end loop;
end Part_2;
procedure Part_3
is
subtype Real is Long_Long_Float;
package Real_IO is new Ada.Text_IO.Float_IO (Real);
package Power_1_1 is new Knuth_Power_Tree (Result_Type => Real,
Base => 1.1,
Identity => 1.0);
R : Real;
begin
Put_Line ("=== Part 3 ===");
for E in 81 .. 84 loop
R := Power_1_1.Power (E);
Put ("1.1 **" & E'Image & " = ");
Real_IO.Put (R, Exp => 0, Aft => 6);
New_Line;
end loop;
end Part_3;
begin
Part_1;
Part_2;
Part_3;
end Power_Tree;</syntaxhighlight>
{{out}}
<pre>
=== Part 1 ===
2 ** 0 = 1
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
2 ** 6 = 64
2 ** 7 = 128
2 ** 8 = 256
2 ** 9 = 512
2 ** 10 = 1024
2 ** 11 = 2048
2 ** 12 = 4096
2 ** 13 = 8192
2 ** 14 = 16384
2 ** 15 = 32768
2 ** 16 = 65536
2 ** 17 = 131072
2 ** 18 = 262144
2 ** 19 = 524288
2 ** 20 = 1048576
2 ** 21 = 2097152
2 ** 22 = 4194304
2 ** 23 = 8388608
2 ** 24 = 16777216
2 ** 25 = 33554432
=== Part 2 ===
3 ** 190 = 4498196224760364601242719132174628305800834098010033971355568455673974002968757862019419449
3 ** 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
3 ** 192 = 40483766022843281411184472189571654752207506882090305742200116101065766026718820758174775041
=== Part 3 ===
1.1 ** 81 = 2253.240236
1.1 ** 82 = 2478.564260
1.1 ** 83 = 2726.420686
1.1 ** 84 = 2999.062754
</pre>
=={{header|EchoLisp}}==
===Power tree===
We build the tree using '''tree.lib''', adding leaves until the target n is found.
<
(lib 'tree)
Line 128 ⟶ 383:
(add-level T init-chain: (make-vector 0) target nums)
))
</syntaxhighlight>
{{out}}
<pre>
Line 168 ⟶ 423:
</pre>
===Exponentiation===
<
;; j such as chain[i] = chain[i-1] + chain[j]
(define (adder chain i)
Line 180 ⟶ 435:
(vector-set! pow i ( * [pow [1- i]] [pow (adder chain i)])))
[pow (1- lg)])
</syntaxhighlight>
{{out}}
<pre>
Line 195 ⟶ 450:
</pre>
=={{header|F_Sharp|F#}}==
===Integer Exponentiation===
<syntaxhighlight lang="fsharp">
// Integer exponentiation using Knuth power tree. Nigel Galloway: October 29th., 2020
let kT α=let n=Array.zeroCreate<int*int list>((pown 2 (α+1))+1)
let fN g=let rec fN p=[yield g+p; if p>0 then let g,_=n.[p] in yield! fN g] in (g+g)::(fN (fst n.[g]))|>List.rev
let fG g=[for α,β in g do for g in β do let p,_=n.[g] in n.[g]<-(p,fN g|>List.filter(fun β->if box n.[β]=null then n.[β]<-(g,[]); true else false)); yield n.[g]]
let rec kT n g=match g with 0->() |_->let n=fG n in kT n (g-1)
let fE X g=let α=let rec fE g=[|yield g; if g>1 then yield! fE (fst n.[g])|] in fE g
let β=Array.zeroCreate<bigint>α.Length
let l=β.Length-1
β.[l]<-bigint (X+0)
for e in l-1.. -1..0 do β.[e]<-match α.[e]%2 with 0->β.[e+1]*β.[e+1] |_->let l=α.[e+1] in β.[e+1]*β.[α|>Array.findIndex(fun n->l+n=α.[e])]
β.[0]
n.[1]<-(0,[2]); n.[2]<-(1,[]); kT [n.[1]] α; (fun n g->if g=0 then 1I else fE n g)
let xp=kT 11
[0..17]|>List.iter(fun n->printfn "2**%d=%A\n" n (xp 2 n))
printfn "3**191=%A" (xp 3 191)
</syntaxhighlight>
{out}
<pre>
2**0=1
2**1=2
2**2=4
2**3=8
2**4=16
2**5=32
2**6=64
2**7=128
2**8=256
2**9=512
2**10=1024
2**11=2048
2**12=4096
2**13=8192
2**14=16384
2**15=32768
2**16=65536
2**17=131072
3**191=13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
===Float Exponentiation===
<syntaxhighlight lang="fsharp">
// Float exponentiation using Knuth power tree. Nigel Galloway: October 29th., 2020
let kTf α=let n=Array.zeroCreate<int*int list>((pown 2 (α+1))+1)
let fN g=let rec fN p=[yield g+p; if p>0 then let g,_=n.[p] in yield! fN g] in (g+g)::(fN (fst n.[g]))|>List.rev
let fG g=[for α,β in g do for g in β do let p,_=n.[g] in n.[g]<-(p,fN g|>List.filter(fun β->if box n.[β]=null then n.[β]<-(g,[]); true else false)); yield n.[g]]
let rec kT n g=match g with 0->() |_->let n=fG n in kT n (g-1)
let fE X g=let α=let rec fE g=[|yield g; if g>1 then yield! fE (fst n.[g])|] in fE g
let β=Array.zeroCreate<float>α.Length
let l=β.Length-1
β.[l]<-X
for e in l-1.. -1..0 do β.[e]<-match α.[e]%2 with 0->β.[e+1]*β.[e+1] |_->let l=α.[e+1] in β.[e+1]*β.[α|>Array.findIndex(fun n->l+n=α.[e])]
β.[0]
n.[1]<-(0,[2]); n.[2]<-(1,[]); kT [n.[1]] α; (fun n g->if g=0 then 1.0 else fE n g)
let xpf=kTf 11
printfn "1.1**81=%f" (xpf 1.1 81)
</syntaxhighlight>
{{out}}
<pre>
1.1**81=2253.240236
</pre>
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 264 ⟶ 584:
showPow(1.1, 81, false)
showPow(3, 191, true)
}</
{{out}}
Line 331 ⟶ 651:
=={{header|Groovy}}==
{{trans|Java}}
<
private static Map<Integer, Integer> p = new HashMap<>()
private static List<List<Integer>> lvl = new ArrayList<>()
Line 392 ⟶ 712:
showPos 3.0, 191, true
}
}</
{{out}}
<pre>0: []
Line 453 ⟶ 773:
191: [1, 2, 4, 8, 16, 32, 64, 128, 160, 176, 184, 188, 190, 191]
3 ^ 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347</pre>
=={{header|Haskell}}==
{{works with|GHC|8.8.1}}
{{libheader|containers|0.6.2.1}}
<syntaxhighlight lang="haskell">{-# LANGUAGE ScopedTypeVariables #-}
module Rosetta.PowerTree
( Natural
, powerTree
, power
) where
import Data.Foldable (toList)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.List (foldl')
import Data.Sequence (Seq (..), (|>))
import qualified Data.Sequence as Seq
import Numeric.Natural (Natural)
type M = Map Natural S
type S = Seq Natural
levels :: [M]
levels = let s = Seq.singleton 1 in fst <$> iterate step (Map.singleton 1 s, s)
step :: (M, S) -> (M, S)
step (m, xs) = foldl' f (m, Empty) xs
where
f :: (M, S) -> Natural -> (M, S)
f (m', ys) n = foldl' g (m', ys) ns
where
ns :: S
ns = m' Map.! n
g :: (M, S) -> Natural -> (M, S)
g (m'', zs) k =
let l = n + k
in case Map.lookup l m'' of
Nothing -> (Map.insert l (ns |> l) m'', zs |> l)
Just _ -> (m'', zs)
powerTree :: Natural -> [Natural]
powerTree n
| n <= 0 = []
| otherwise = go levels
where
go :: [M] -> [Natural]
go [] = error "impossible branch"
go (m : ms) = fromMaybe (go ms) $ toList <$> Map.lookup n m
power :: forall a. Num a => a -> Natural -> a
power _ 0 = 1
power a n = go a 1 (Map.singleton 1 a) $ tail $ powerTree n
where
go :: a -> Natural -> Map Natural a -> [Natural] -> a
go b _ _ [] = b
go b k m (l : ls) =
let b' = b * m Map.! (l - k)
m' = Map.insert l b' m
in go b' l m' ls</syntaxhighlight>
{{out}}
{{libheader|numbers|3000.2.0.2}}
(The <tt>CReal</tt> type from package <tt>numbers</tt> is used to get the ''exact'' result for the last example.)
<pre>
powerTree 0 = [], power 2 0 = 1
powerTree 1 = [1], power 2 1 = 2
powerTree 2 = [1,2], power 2 2 = 4
powerTree 3 = [1,2,3], power 2 3 = 8
powerTree 4 = [1,2,4], power 2 4 = 16
powerTree 5 = [1,2,3,5], power 2 5 = 32
powerTree 6 = [1,2,3,6], power 2 6 = 64
powerTree 7 = [1,2,3,5,7], power 2 7 = 128
powerTree 8 = [1,2,4,8], power 2 8 = 256
powerTree 9 = [1,2,3,6,9], power 2 9 = 512
powerTree 10 = [1,2,3,5,10], power 2 10 = 1024
powerTree 11 = [1,2,3,5,10,11], power 2 11 = 2048
powerTree 12 = [1,2,3,6,12], power 2 12 = 4096
powerTree 13 = [1,2,3,5,10,13], power 2 13 = 8192
powerTree 14 = [1,2,3,5,7,14], power 2 14 = 16384
powerTree 15 = [1,2,3,5,10,15], power 2 15 = 32768
powerTree 16 = [1,2,4,8,16], power 2 16 = 65536
powerTree 17 = [1,2,4,8,16,17], power 2 17 = 131072
powerTree 191 = [1,2,3,5,7,14,19,38,57,95,190,191], power 3 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
powerTree 81 = [1,2,3,5,10,20,40,41,81], power 1.1 81 = 2253.240236044012487937308538033349567966729852481170503814810577345406584190098644811
</pre>
=={{header|J}}==
Line 462 ⟶ 869:
We can represent the tree as a list of indices. Each entry in the list gives the value of <code>n</code> for the index <code>a+n</code>. (We can find <code>a</code> using subtraction.)
<
L=: P=: %(1+y){._ 1
findpath=: ]
Line 489 ⟶ 896:
end.
{:exp
)</
Task examples:
<
0 1 1 2 2 3 3 5 4 6 5 10 6 10 7 10 8 16 9 14 10 14 11 13 12 15 13 18 14 28 15 28 16 17 17 21 18 36 19 26 20 40 21 40 22 30 23 42 24 48 25 48 26 52 27 44 28 38 29 31 30 56 31 42 32 64 33 66 34 46 35 57 36 37 37 50 38 76 39 76 40 41 41 43 42 80 43 84 44 47 45 70 46 62 47 57 48 49 49 51 50 100 51 100 52 70 53 104 54 104 55 108 56 112 57 112 58 61 59 112 60 120 61 120 62 75 63 126 64 65 65 129 66 67 67 90 68 136 69 138 70 140 71 140 72 144 73 144 74 132 75 138 76 144 77 79 78 152 79 152 80 160 81 160 82 85 83 162 84 168 85 114 86 168 87 105 88 118 89 176 90 176 91 122 92 184 93 176 94 126 95 190
Line 595 ⟶ 1,002:
(x:1.1) usepath 81
2253240236044012487937308538033349567966729852481170503814810577345406584190098644811r1000000000000000000000000000000000000000000000000000000000000000000000000000000000
</syntaxhighlight>
Note that an 'r' in a number indicates a rational number with the numerator to the left of the r and the denominator to the right of the r. We could instead use decimal notation by indicating how many characters of result we want to see, as well as how many characters to the right of the decimal point we want to see.
Line 601 ⟶ 1,008:
Thus, for example:
<
2253.24023604401248793730853803334956796672985248117050381481057734540658419009864481100</
=={{header|Java}}==
{{trans|Kotlin}}
<
import java.util.ArrayList;
import java.util.HashMap;
Line 672 ⟶ 1,079:
showPow(3.0, 191, true);
}
}</
{{out}}
<pre>0: []
Line 733 ⟶ 1,140:
191: [1, 2, 4, 8, 16, 32, 64, 128, 160, 176, 184, 188, 190, 191]
3 ^ 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347</pre>
=={{header|jq}}==
'''Adapted from [[#Wren]]'''
'''Works with [[jq]]''' (*)
'''Works with gojq, the Go implementation of jq'''
(*) Use gojq for infinite-precision integer arithmetic.
<syntaxhighlight lang="jq"># Input: {p, lvl, path}
def kpath($n):
if $n == 0 then .path=[]
else until( .p[$n|tostring];
.q = []
| reduce .lvl[0][] as $x (.;
kpath($x)
| label $out
| foreach (.path[], null) as $y (.;
if $y == null then .
else (($x + $y)|tostring) as $xy
| if .p[$xy] then .
else .p[$xy] = $x
| .q += [$x + $y]
end
end;
select($y == null) ) )
| .lvl[0] = .q )
| kpath(.p[$n|tostring])
| .path += [$n]
end ;
# Input: as for kpath
def treePow($x; $n):
reduce kpath($n).path[] as $i (
{r: { "0": 1, "1": $x }, pp: 0 };
.r[$i|tostring] = .r[($i - .pp)|tostring] * .r[.pp|tostring]
| .pp = $i )
| .r[$n|tostring] ;
def showPow($x; $n):
{ p: {"1": 0},
lvl: [[1]],
path: []}
| "\($n): \(kpath($n).path)",
"\($x) ^ \($n) = \(treePow($x; $n))";
(range(0;18) as $n | showPow(2; $n)),
showPow(1.1; 81),
showPow(3; 191)</syntaxhighlight>
{{out}}
Using gojq, the output is the same as for [[#Wren|Wren]].
=={{header|Julia}}==
Line 738 ⟶ 1,197:
'''Module''':
<
const p = Dict(1 => 0)
Line 769 ⟶ 1,228:
end
end # module KnuthPowerTree</
'''Main''':
<
for n in 0:17
Line 780 ⟶ 1,239:
for (x, n) in ((big(3), 191), (1.1, 81))
println("$x ^ $n:\n - path: ", join(path(n), ", "), "\n - result: ", pow(x, n))
end</
{{out}}
Line 846 ⟶ 1,305:
=={{header|Kotlin}}==
{{trans|Python}}
<
import java.math.BigDecimal
Line 889 ⟶ 1,348:
showPow(1.1, 81, false)
showPow(3.0, 191)
}</
{{out}}
Line 953 ⟶ 1,412:
3 ^ 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[NextStep, TreePow]
NextStep[pows_List] := Module[{maxlen, sel, new, vals, knows},
maxlen = Max[Length /@ pows[[All, "Path"]]];
sel = Select[pows, Length[#["Path"]] == maxlen &];
knows = pows[[All, "P"]];
new = {};
Do[
vals = s["P"] + s["Path"];
vals = DeleteCases[vals, Alternatives @@ Join[s["Path"], knows]];
new =
Join[
new, <|"Path" -> Append[s["Path"], #], "P" -> #|> & /@ vals];
,
{s, sel}
];
new //= DeleteDuplicatesBy[#["P"] &];
SortBy[Join[pows, new], #["P"] &]
]
TreePow[path_List, base_] := Module[{db, tups},
db = <|1 -> base|>;
Do[
tups = Tuples[Keys[db], 2];
tups = Select[tups, #[[2]] >= #[[1]] &];
tups = Select[tups, Total[#] == next &];
If[Length[tups] < 1, Abort[]];
tups //= First;
AssociateTo[db, Total[tups] -> (Times @@ (db /@ tups))]
,
{next, Rest[path]}
];
db[Last[path]]
]
pows = {<|"Path" -> {1}, "P" -> 1|>};
steps = Nest[NextStep, pows, 7];
LayeredGraphPlot[DirectedEdge @@@ steps[[2 ;;, "Path", -2 ;;]], VertexLabels -> Automatic]
pows = {<|"Path" -> {1}, "P" -> 1|>};
steps = Nest[NextStep, pows, 5];
assoc = Association[#["P"] -> #["Path"] & /@ steps];
Dataset[assoc]
TreePow[assoc[#], 2] & /@ Range[1, 17]
pows = {<|"Path" -> {1}, "P" -> 1|>};
steps = NestWhile[NextStep, pows, Not[MemberQ[#[[All, "P"]], 191]] &];
SelectFirst[steps, #["P"] == 191 &]["Path"];
TreePow[%, 3]
pows = {<|"Path" -> {1}, "P" -> 1|>};
steps = NestWhile[NextStep, pows, Not[MemberQ[#[[All, "P"]], 81]] &];
SelectFirst[steps, #["P"] == 81 &]["Path"];
TreePow[%, 1.1]</syntaxhighlight>
{{out}}
<pre>[Graphics object showing the tree]
1 {1}
2 {1,2}
3 {1,2,3}
4 {1,2,4}
5 {1,2,3,5}
6 {1,2,3,6}
7 {1,2,3,5,7}
8 {1,2,4,8}
9 {1,2,3,6,9}
10 {1,2,3,5,10}
11 {1,2,3,6,9,11}
12 {1,2,3,6,12}
13 {1,2,3,5,10,13}
14 {1,2,3,5,7,14}
15 {1,2,3,6,9,15}
16 {1,2,4,8,16}
17 {1,2,4,8,16,17}
18 {1,2,3,6,9,18}
20 {1,2,3,5,10,20}
24 {1,2,3,6,12,24}
... ...
{2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072}
13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
2253.24</pre>
=={{header|Nim}}==
{{trans|Kotlin}}
{{libheader|bignum}}
This is a translation of the Kotlin/Python program. The algorithm is the same but there are some changes: replacement of global variables by a tree object, use of longer names, replacement of the "lvl" list of lists by a simple list, use of generics to handle the case of big integers...
<syntaxhighlight lang="nim">import tables
import bignum
type
Id = Natural # Node identifier (= exponent value).
Tree = object
parents: Table[Id, Id] # Mapping node id -> parent node id.
lastLevel: seq[Id] # List of node ids in current last level.
func initTree(): Tree =
## Return an initialized tree.
const Root = Id(1)
Tree(parents: {Root: Id(0)}.toTable, lastLevel: @[Root])
func path(tree: var Tree; id: Id): seq[Id] =
## Return the path to node with given id.
if id == 0: return
while id notin tree.parents:
# Node "id" not yet present in the tree: build a new level.
var newLevel: seq[Id]
for x in tree.lastLevel:
for y in tree.path(x):
let newId = x + y
if newId in tree.parents: break # Node already created.
# Create a new node.
tree.parents[newId] = x
newLevel.add newId
tree.lastLevel = move(newLevel)
# Node path is the concatenation of parent node path and node id.
result = tree.path(tree.parents[id]) & id
func treePow[T: SomeNumber | Int](tree: var Tree; x: T; n: Natural): T =
## Compute x^n using the power tree.
let one = when T is Int: newInt(1) else: T(1)
var results = {0: one, 1: x}.toTable # Intermediate and last results.
var k = 0
for i in tree.path(n):
results[i] = results[i - k] * results[k]
k = i
return results[n]
proc showPow[T: SomeNumber | Int](tree: var Tree; x: T; n: Natural) =
echo n, " → ", ($tree.path(n))[1..^1]
let result = tree.treePow(x, n)
echo x, "^", n, " = ", result
when isMainModule:
var tree = initTree()
for n in 0..17: tree.showPow(2, n)
echo ""
tree.showPow(1.1, 81)
echo ""
tree.showPow(newInt(3), 191)</syntaxhighlight>
{{out}}
<pre>0 → []
2^0 = 1
1 → [1]
2^1 = 2
2 → [1, 2]
2^2 = 4
3 → [1, 2, 3]
2^3 = 8
4 → [1, 2, 4]
2^4 = 16
5 → [1, 2, 4, 5]
2^5 = 32
6 → [1, 2, 4, 6]
2^6 = 64
7 → [1, 2, 4, 6, 7]
2^7 = 128
8 → [1, 2, 4, 8]
2^8 = 256
9 → [1, 2, 4, 8, 9]
2^9 = 512
10 → [1, 2, 4, 8, 10]
2^10 = 1024
11 → [1, 2, 4, 8, 10, 11]
2^11 = 2048
12 → [1, 2, 4, 8, 12]
2^12 = 4096
13 → [1, 2, 4, 8, 12, 13]
2^13 = 8192
14 → [1, 2, 4, 8, 12, 14]
2^14 = 16384
15 → [1, 2, 4, 8, 12, 14, 15]
2^15 = 32768
16 → [1, 2, 4, 8, 16]
2^16 = 65536
17 → [1, 2, 4, 8, 16, 17]
2^17 = 131072
81 → [1, 2, 4, 8, 16, 32, 64, 80, 81]
1.1^81 = 2253.240236044025
191 → [1, 2, 4, 8, 16, 32, 64, 128, 160, 176, 184, 188, 190, 191]
3^191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347</pre>
=={{header|Perl}}==
<
my %p = (1 => 0);
Line 998 ⟶ 1,655:
use bigint (try => 'GMP');
show_pow(3, 191);
}</
{{out}}
<pre style="height:32ex;overflow:scroll">
Line 1,041 ⟶ 1,698:
191: (1 2 4 8 16 32 64 128 160 176 184 188 190 191)
3^191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
=={{header|Phix}}==
{{trans|Go}}
{{libheader|Phix/mpfr}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}})</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lvl</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">path</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">getd_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lvl</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lvl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">px</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">path</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">px</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">px</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">getd_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)!=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">q</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">y</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">lvl</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">q</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">path</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">))&</span><span style="color: #000000;">n</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #7060A8;">mpfr_set_default_precision</span><span style="color: #0000FF;">(</span><span style="color: #000000;">500</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">treepow</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">pn</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{})</span>
<span style="color: #000080;font-style:italic;">-- x can be atom or string (but not mpfr)
-- (asides: sequence r uses out-by-1 indexing, ie r[1] is for 0.
-- sequence c is used to double-check we are not trying
-- to use something which has not yet been calculated.)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">pn</span><span style="color: #0000FF;">={}</span> <span style="color: #008080;">then</span> <span style="color: #000000;">pn</span><span style="color: #0000FF;">=</span><span style="color: #000000;">path</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)},</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">mpfr_init</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pn</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pn</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">-</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpfr_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">-</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pi</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pi</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- string res = shorten(trim_tail(mpfr_sprintf("%.83Rf",r[n+1]),".0"))</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">trim_tail</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">83</span><span style="color: #0000FF;">),</span><span style="color: #008000;">".0"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpfr_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">showpow</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">pn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">path</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">xs</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)?</span><span style="color: #000000;">x</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%3g"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%48v : %3s ^ %d = %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">pn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">xs</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">treepow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pn</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">17</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">showpow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">showpow</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.1"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">81</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">showpow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">191</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 12px">
{} : 2 ^ 0 = 1
{1} : 2 ^ 1 = 2
Line 1,170 ⟶ 1,786:
{1,2,4,8,16} : 2 ^ 16 = 65536
{1,2,4,8,16,17} : 2 ^ 17 = 131072
{1,2,4,8,16,32,64,80,81} : 1.1 ^ 81 = 2253.
{1,2,4,8,16,32,64,128,160,176,184,188,190,191} : 3 ^ 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
=={{header|Python}}==
<
# remember the tree generation state and expand on demand
Line 1,202 ⟶ 1,818:
for x in range(18): show_pow(2, x)
show_pow(3, 191)
show_pow(1.1, 81)</
{{out}}
<pre>
Line 1,228 ⟶ 1,844:
=={{header|Racket}}==
{{trans|Python}}
<
(define pow-path-cache (make-hash '((0 . (0)) (1 . (0 1)))))
Line 1,267 ⟶ 1,883:
(show-pow 2 x))
(show-pow 3 191)
(show-pow 1.1 81)</
{{out}}
<pre>0: ()
Line 1,309 ⟶ 1,925:
81: (1 2 3 5 10 20 40 41 81)
1.1^81 = 2253.2402360440283</pre>
=={{header|Raku}}==
(formerly Perl 6)
Paths are random. It is possible replace <code>.pick(*)</code> with <code>.reverse</code> if you want paths as in Perl, or remove it for Python paths.
<syntaxhighlight lang="raku" line>use v6;
sub power-path ($n ) {
state @unused_nodes = (2,);
state @power-tree = (False,0,1);
until @power-tree[$n].defined {
my $node = @unused_nodes.shift;
for $node X+ power-path($node).pick(*) {
next if @power-tree[$_].defined;
@unused_nodes.push($_);
@power-tree[$_]= $node;
}
}
( $n, { @power-tree[$_] } ...^ 0 ).reverse;
}
multi power ( $, 0 ) { 1 };
multi power ( $n, $exponent ) {
state %p;
my %r = %p{$n} // ( 0 => 1, 1 => $n ) ;
for power-path( $exponent ).rotor( 2 => -1 ) -> ( $p, $c ) {
%r{ $c } = %r{ $p } * %r{ $c - $p }
}
%p{$n} := %r ;
%r{ $exponent }
}
say 'Power paths: ', pairs map *.&power-path, ^18;
say '2 ** key = value: ', pairs map { 2.&power($_) }, ^18;
say 'Path for 191: ', power-path 191;
say '3 ** 191 = ', power 3, 191;
say 'Path for 81: ', power-path 81;
say '1.1 ** 81 = ', power 1.1, 81;
</syntaxhighlight>
{{out}}
<pre>
Power paths: (0 => () 1 => (1) 2 => (1 2) 3 => (1 2 3) 4 => (1 2 4) 5 => (1 2 3 5) 6 => (1 2 3 6) 7 => (1 2 3 6 7) 8 => (1 2 4 8) 9 => (1 2 3 6 9) 10 => (1 2 3 5 10) 11 => (1 2 3 6 9 11) 12 => (1 2 3 6 12) 13 => (1 2 3 6 12 13) 14 => (1 2 3 6 12 14) 15 => (1 2 3 6 9 15) 16 => (1 2 4 8 16) 17 => (1 2 4 8 16 17))
2 ** key = value: (0 => 1 1 => 2 2 => 4 3 => 8 4 => 16 5 => 32 6 => 64 7 => 128 8 => 256 9 => 512 10 => 1024 11 => 2048 12 => 4096 13 => 8192 14 => 16384 15 => 32768 16 => 65536 17 => 131072)
Path for 191: (1 2 3 6 9 18 27 54 108 162 189 191)
3 ** 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
Path for 81: (1 2 3 6 9 18 27 54 81)
1.1 ** 81 = 2253.24023604401
</pre>
=={{header|REXX}}==
Line 1,314 ⟶ 1,983:
Also, negative powers are supported.
<
numeric digits 1000 /*be able to handle some large numbers.*/
parse arg XP /*get sets: X, low power, high power.*/
Line 1,320 ⟶ 1,989:
/*────── X LP HP X LP HP X LP ◄── X, low power, high power ··· repeat*/
do until XP=''
parse var XP x pL pH XP; x= x /
if pH='' then pH=
do e=pL to pH;
$= powerTree(p);
/* [↑] W≡length for an aligned display*/
if p==0 then do; z= 1; call show; iterate; end
!.= .; z= x; !.1= z;
do k=2 to words($); n= @.k
prev= k - 1; diff= n - @.prev
if n//2==0 then z= prv **
else z= z * !.diff
!.n=
prv=
end /*k*/
call show /*display the expression and its value.*/
end /*e*/
end /*until XP ···*/
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
powerTree: arg y 1 oy; $= /*Z is the result; $ is the power tree.*/
if y=0 | y=1 then return y /*handle special cases for zero & unity*/
#.= 0; @.= 0; #.0=
/* [↓] add blank "flag" thingy──►list.*/
do while \(y//2); $=
if y\==oy then $= y $
y= y %
end /*while*/
if $\=='' then $= y $
$= $ oy
if y>1 then do while @.y==0; n= #.0; m= 0
do while n\==0; q= 0; s= n
do while s\==0; _= n + s
if @._==0 then do; if q==0 then m_=
#._= q; @._= n; q= _
end
s= @.s
end /*while s¬==0*/
if q\==0 then do; #.m= q; m= m_; end
n= #.n
end /*while n¬==0*/
#.m= 0
end /*while @.y==0*/
z= @.y
do while z\==0; $= z $; z= @.z; end
return space($) /*del extra blanks*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: if e<0 then z=format(1/z, , 40)/1; _=right(e, w) /*use reciprocal? */
say left('power tree for ' _ " is: " $,60) '═══' x"^"_ ' is: ' z; return</
<pre>
power tree for -4 is: 1 2 4 ═══ 2^-4 is: 0.0625
Line 1,403 ⟶ 2,073:
=={{header|Sidef}}==
{{trans|zkl}}
<
var p = Hash(1 => 0)
Line 1,440 ⟶ 2,110:
for x in ^18 { show_pow(2, x) }
show_pow(1.1, 81)
show_pow(3, 191)</
{{out}}
<pre style="height:32ex;overflow:scroll">
Line 1,483 ⟶ 2,153:
191: [1, 2, 4, 8, 16, 32, 64, 128, 160, 176, 184, 188, 190, 191]
3^191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./big" for BigRat
import "./fmt" for Fmt
var p = { 1: 0 }
var lvl = [[1]]
var path // recursive
path = Fn.new { |n|
if (n == 0) return []
while (!p.containsKey(n)) {
var q = []
for (x in lvl[0]) {
System.write("") // guard against VM recursion bug
for (y in path.call(x)) {
if (p.containsKey(x + y)) break
p[x + y] = x
q.add(x + y)
}
}
lvl[0] = q
}
System.write("") // guard against VM recursion bug
var l = path.call(p[n])
l.add(n)
return l
}
var treePow = Fn.new { |x, n|
var r = { 0: BigRat.one, 1: BigRat.fromDecimal(x) }
var p = 0
for (i in path.call(n)) {
r[i] = r[i-p] * r[p]
p = i
}
return r[n]
}
var showPow = Fn.new { |x, n|
System.print("%(n): %(path.call(n))")
Fmt.print("$s ^ $d = $s\n", x, n, treePow.call(x, n).toDecimal(6))
}
for (n in 0..17) showPow.call(2, n)
showPow.call(1.1, 81)
showPow.call(3, 191)</syntaxhighlight>
{{out}}
<pre>
0: []
2 ^ 0 = 1
1: [1]
2 ^ 1 = 2
2: [1, 2]
2 ^ 2 = 4
3: [1, 2, 3]
2 ^ 3 = 8
4: [1, 2, 4]
2 ^ 4 = 16
5: [1, 2, 4, 5]
2 ^ 5 = 32
6: [1, 2, 4, 6]
2 ^ 6 = 64
7: [1, 2, 4, 6, 7]
2 ^ 7 = 128
8: [1, 2, 4, 8]
2 ^ 8 = 256
9: [1, 2, 4, 8, 9]
2 ^ 9 = 512
10: [1, 2, 4, 8, 10]
2 ^ 10 = 1024
11: [1, 2, 4, 8, 10, 11]
2 ^ 11 = 2048
12: [1, 2, 4, 8, 12]
2 ^ 12 = 4096
13: [1, 2, 4, 8, 12, 13]
2 ^ 13 = 8192
14: [1, 2, 4, 8, 12, 14]
2 ^ 14 = 16384
15: [1, 2, 4, 8, 12, 14, 15]
2 ^ 15 = 32768
16: [1, 2, 4, 8, 16]
2 ^ 16 = 65536
17: [1, 2, 4, 8, 16, 17]
2 ^ 17 = 131072
81: [1, 2, 4, 8, 16, 32, 64, 80, 81]
1.1 ^ 81 = 2253.240236
191: [1, 2, 4, 8, 16, 32, 64, 128, 160, 176, 184, 188, 190, 191]
3 ^ 191 = 13494588674281093803728157396523884917402502294030101914066705367021922008906273586058258347
</pre>
=={{header|zkl}}==
{{trans|Python}}
<
fcn path(n,p=Dictionary(1,0),lvl=List(List(1))){
if(n==0) return(T);
Line 1,511 ⟶ 2,294:
fmt:="%d: %s\n" + T("%g^%d = %f", "%d^%d = %d")[x==Int(x)] + "\n";
println(fmt.fmt(n,p:=path(n),x,n,tree_pow(x,n,p)))
}</
<
show_pow(1.1,81);
var [const] BN=Import("zklBigNum"); // GNU GMP big ints
show_pow(BN(3),191);</
{{out}}
<pre style="height:32ex;overflow:scroll">
|