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.

  • $\begingroup$ This problem might be similar to this. $\endgroup$ – xzczd May 9 '16 at 2:05

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...

  • $\begingroup$ 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. $\endgroup$ – Giovanni Resta May 6 '16 at 11:27
  • $\begingroup$ @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 $\endgroup$ – bobbym May 9 '16 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.