## Perfect Power Sequence

### February 16, 2018

I discovered the Numberphile channel on YouTube a few months ago, and have greatly enjoyed its videos at the intersection of mathematics and programming. Their recent video discusses the Catalan Conjecture:

In the infinite sequence of perfect powers 1, 4, 8, 9, 16, 25, 32, 36, 49, 64, 81, 100, …, the only two adjacent numbers are 2³ = 8 and 3² = 9.

The conjecture has recently been proved, as discussed at Numberphile.

Your task is to write a program that generates the perfect power sequence. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisements

Pages: 1 2

Here is my implementation in Julia.

function IsPerfectPower(x::Int64)

y = ceil(Int64, sqrt(x))

end

function genseq(n::Int64)

y = zeros(Int64, n)

y[1] = 1

end

Performance benchmark: on an Intel i7 laptop running on Win7, it generates the sequence of the PP numbers that are less or equal to 10000 in about 0.1 sec, using approx. 85 MB of RAM.

Typo in my previous commend: 85 Kilobytes, not MB… Sorry about that!

Two solutions in Python. I expected the first to be the fastest: merging already sorted sequences. But it turned out to be otherwise. The second is a little faster.

Here is some Java. It generates up to 10000 in around 60ms on a 3.3GHz i5 iMac:

The queue solution works nicely in Python:

It’s quite important how the queue is extended – doing

still works, but the queue gets much longer.

Incidentally, the code on the solution page seems to be garbled – I think WordPress have messed something up with angle brackets in code.

By the way, this is https://oeis.org/A001597

@matthew: I tried the priority method too and it worked nicely, but a little slow in Python. The method below takes about 0.1 sec for all powers below 10^9.

@Paul: did you do a speed comparison with my priority queue function above?

@matthew: I see now that your method works very fast (91 msec for yours and 121 ms for pp2 for all powers up to 10^9). I must have messed up something with my implementation.

@Paul: that’s about what I made it – also the queue uses less memory, I’m running the program just printing out all the numbers, up to 25528390307779969 after about 30 mins.

For the queue, as mentioned above, it’s significant how the queue is extended.

Here’s an implementation in C that uses the approach from the solution.

Output: