I am looking for a reasonably fast algorithm to calculate terms of the OEIS sequence A002845. Let me restate its definition here.
Let ^ denote the exponentiation operator. Consider expressions of the form 2^2^...^2 having n 2's with parentheses inserted in all possible ways (the number of possible parenthesizations is given by Catalan numbers). Some of these expressions will have the same value, for example (2^2)^2=2^(2^2). We are interested in the number of distinct values for a given n.
There is an obvious brute-force solution through a direct calculation of these expressions, but it is clear that the required time and space quickly exceed all reasonable limits even for relatively small n. I'm interested in a polynomial-time solution to this problem.
Just represent the numbers in iterated base 2: a Num
has a (possibly empty) list of distinct children x1,...,xp
of type Num
, so that Num([x1,...,xp]) == 2^x1 + ... + 2^xp
.
This defines a unique way to write a nonnegative integer; remember to sort the exponents so that comparison makes sense. The equalities:
2^x + 2^x == 2^(x+1) == Num([x+1])
2^x + 2^y == Num([x,y])
when x != y
(2^2^x)^2^y == 2^2^(x+y) == Num([Num([x+y])])
along with associativity/commutativity of addition allow you to add arbitrary numbers and compute x^y
for numbers of the form 2^2^k; this class of numbers contains 2 (with k=0) and is closed under ^
so this guarantees that every number we need to manipulate is of this form.
Furthermore, the equalities defined above never increase the number of nodes in the tree, so all the Num
are of size O(n)
.
So the time complexity is actually O(C * n^k)
which is quasi-linear in C (C is the (n-1)-th Catalan number).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With