Perfect Power
Last updated
Last updated
A Power Number is defined as a number greater than zero that can be expressed as X^Y, where X and Y are integers greater than one. Thus, the first few (in order) are:
This function takes an integer i and returns the (zero-indexed) ith power number. Some examples:
The Idea: A perfect power begins at the power and exponent position 2^2. Then it could proceed in either one of two directions (to the left it, or to the element below it). That is, it can either transition to 2^3 or 3^2 from 2^2. As far we know for now, the result can exist is either direction, so both siblings are added to the queue. Repeat this step for the next element in the queue. Notice how doing so covers the entirety of the matrix.
Complexity: O(nlogn) time. The priority queue has to manage at least one more element than it takes out, so its size increases linearly, and so each subsequent operation will take log(k+1) more work, where k begins at 0 and increases by one n amount of times where n is the total number of elements in the matrix. O(n/2) space
The Idea: The technique that I'll go through here is really cool. If we combine generators with a heap, all of our micro operations can be managed within the heap and the logic of the code simplifies. First, begin with i
generators, where i
is [0...index]
. Each generator carries out infinite operation of i^n
for n=[0,1,2...inf]
. Our heap will continue to maintain i
generator objects, but our root of our heap will contain the current minimum value held to a generator. Calling next()
on this generator object will place it elsewhere in the tree, and the next minimum generator object will appear upfront. Complexity: O(nlogn) time and O(n) space where n is the index