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?
Nis a reserved symbol. You should get an error message if you try to assign a value to it. – kglr Jul 21 '19 at 18:55maxi. – SmileyCraft Jul 21 '19 at 18:56maxi? – kglr Jul 21 '19 at 19:01Tablein the documentation. – Henrik Schumacher Jul 21 '19 at 19:08Tableis used to create a list, not to append something to a list or to change the elements of a list, so I do not see how that helps me. – SmileyCraft Jul 21 '19 at 19:15Association, (ii)SowandReap, or (iii)Internal`Bag. The latter is not documented, though, but you can find details about it on this site. – Henrik Schumacher Jul 21 '19 at 19:28