I have the following c++ code that I want to translate to Mathematica.
std::vector<int> squbes;
for (int p : primes) for (int q : primes) if (p != q){
if (p*p*q*q*q > maxi) break;
squbes.push_back(p*p*q*q*q);
}
As you can see I simply have a list of numbers that I want to iteratively append elements to.
The first thing I tried was the following functional approach.
sqube[{x_,y_}] := x*x*y*y*y
unequal[{x_, y_}] := x != y
smallenough[x_] := x <= maxi
pairs := Select[Tuples[primes, 2], unequal]
squbes := Select[Map[sqube, pairs], smallenough]
However this is way too slow because it misses the very important break condition in the loop in the c++ version.
Next I tried the most direct translation I could come up with.
sqube[{x_,y_}] := x*x*y*y*y
squbes := {}
For[i = 1, i <= Length[primes], i++,
For[j = 1, j <= Length[primes] && sqube[{primes[[i]], primes[[j]]}] <= maxi, j++,
AppendTo[squbes, sqube[{primes[[i]], primes[[j]]}]]]]
However for some reason this turned out to be really slow, even if primes
has only $100$ elements it took more than a second. I suspect AppendTo
creates a completely new list every time?
The final thing I tried was to use ReplacePart
, but the attempt is not even worth showing. First problem is that you need to initialize squbes
to be large enough, even though I have no good idea how large it will be. Second problem is that I see no reason to assume that ReplacePart
will not create a completely new list every time.
Can you please help me simply create this list of squbes in a decent amount of time?
N
is a reserved symbol. You should get an error message if you try to assign a value to it. $\endgroup$maxi
. $\endgroup$maxi
? $\endgroup$Association
, (ii)Sow
andReap
, or (iii)Internal`Bag
. The latter is not documented, though, but you can find details about it on this site. $\endgroup$