Earlier I posted a question about taking fast integer square roots of known integer perfect squares.
The reason this came up is I was trying to find a faster way of mimicking the PowersRepresentations[] function in Mathematica.
Using IntegerPartitions[] I can speed up this by quite a bit - but then I needed to take the square roots of the output from IntegerPartitions - which ends up costing me about a factor of two or three in speed. Though still a lot faster than using PowersRepresentations[] directly.
For example:
n = 8174;
parts = 6;
Length@PowersRepresentations[n, parts, 2] // AbsoluteTiming
(* {1.1861, 31934} *)
Length@IntegerPartitions[n, {parts},
Range[0, IntegerPart[Sqrt[n]]]^2] // AbsoluteTiming
(* {0.021446, 31934} *)
Length@Round[
Sqrt[N[
IntegerPartitions[n, {parts},
Range[0, IntegerPart[Sqrt[n]]]^2]]]] // AbsoluteTiming
(* {0.039502, 31934} *)
This might be a silly wish - but is there a way of cutting out the middle man so to speak. I'd like the output of IntegerPartitions[] to be the integers themselves and not their squares. This seems unlikely but does anyone know a workaround or am I destined to have to take the square roots after the fact? Having said this I would think a workaround would be no faster anyway. I'll delete the question if it is asking the impossible.
(Oh, and one thing that puzzles me - why does PowersRepresentations[] run so much faster on a repeat run even if I clear the system cache?)
NumberTheory`IntegerSqrt
. It offers a small speed boost overIntegerPart@Sqrt
$\endgroup$n = 8174; parts = 6; sqrt = Compile[{{x, _Integer}}, IntegerPart[Sqrt[x]], RuntimeAttributes -> {Listable}]; Length@sqrt[IntegerPartitions[n, {parts}, Range[0, sqrt[n]]^2]] // AbsoluteTiming
$\endgroup$