Is it better to completely forget about the existence of PowersRepresentations?



I noticed that in several cases the performance of PowersRepresentations is hugely worse than that of IntegerPartitions. (Mma 10.3.1)

PowersRepresentations[n,k,p] finds the representations of $n$ as a sum of $k$ non-negative $p$-th powers.

I can define a similar function like


When I compare the performances the difference is huge. Like

AbsoluteTiming[t = Table[PowersRepresentations[12^6+j, 3, 3], {j, 100}];]

takes 21.87 seconds, while

AbsoluteTiming[tt = Table[pr[12^6 + j, 3, 3], {j, 100}];]

takes 0.02802 seconds, which is about 1/780 of the time!

Moreover, using IntegerPartitions I can easily avoid (changing the Range) those representations that contains zeros, a thing that I can only do filtering the results with PowersRepresentations.

So, what I would like to ask is: I'm doing something wrong? If not, has PowersRepresentations some redeeming quality that I'm missing (apart that it caches its results so it can mess up timings...)? Or should it be better to completely forget about its existence? Thanks.

Giovanni Resta

Posted 2016-04-28T12:37:33.367

Reputation: 733

This problem might be similar to this.

– xzczd – 2016-05-09T02:05:06.193



Sure, try for example:

pr[14709321003111578837870501266345370175409, 2, 2]

There are many things in MMA where small cases/edge cases can be done much more quickly with user code, this is one of them.

The advantage here is that PowersRepresentation can handle huge cases...


Posted 2016-04-28T12:37:33.367

Reputation: 23 752

Thanks. It can handle huge cases for n = x^2+y^2, because there is a well-known algorithm to obtain the representation of n as x^2+y^2 given the prime factorization of n. I'm rather confident that in all the other cases (3 squares, 2 cubes, etc.etc.) it has no advantages. By the way, they could have exploited the ability to perform n = x^2+y^2 fast in the search of similar decompositions with even exponents, like n=x^4+y^4, but apparently they didn't. – Giovanni Resta – 2016-05-06T11:27:25.173

@ciao It is mind boggling to hear that you can write faster code than a built in command. Are they not optimized and compiled or written in C++? It never sunk in that the built in command might be a real dog until now. Thanks. +1 – bobbym – 2016-05-09T00:01:52.007