I need some help optimizing a Mathematica code so that it'll not max out RAM. Here's the code:
Cell 1
twinPrimesQ[tp_] :=
tp[[1]] + 2 == tp[[2]] && PrimeQ[tp[[1]]] && PrimeQ[tp[[2]]];
primesList[p_] := Module[{out = {Prime[3]}, i},
For[i = 4, Prime[i] <= p, i = i + 1,
out = Append[out, Prime[i]];
];
out
];
testPrime[p_, pl_] :=
Module[{out, found = False, twinPrimes, primeFactors,
primeFactorsPowers, i},
twinPrimes = {
{3 5 prod p - 4, 3 5 prod p - 2},
{3 5 prod p + 2, 3 5 prod p + 4}
};
primeFactors = primesList[p];
primeFactorsPowers = Tuples[Range[0, pl], primeFactors // Length];
For[i = 1, i <= Length[primeFactorsPowers], i = i + 1,
out =
twinPrimes /.
prod -> Product[
primeFactors[[k]]^primeFactorsPowers[[i]][[k]], {k, 1,
primeFactors // Length}];
found = twinPrimesQ[out[[1]]] || twinPrimesQ[out[[2]]];
If[found, Break[]];
];
If[found, out~Select~(twinPrimesQ[#] &) // First, False]
];
Cell 2
testPrime[109, 1]
Cell 3
out = List[]; For[j = 30, j <= 30, j = j + 1,
out = out~
Append~{j, Prime[j], testPrime[Prime[j], 1]}]; out // TableForm
The code returns the first twin prime found that fits {3 5 prod p - 4, 3 5 prod p - 2}, {3 5 prod p + 2, 3 5 prod p + 4}
where $p$ is a product of primes between 3 and the first input in cells 2 and 3.
Thanks for your help in advance!
i = 29, i <= 29
in cell 3 for the 29th prime, 113. I can even have cell 3 run 'i = 4, i <= 28` with no issues, but for some reason it can't do the 29th prime or above without maxing out memory. I'm thinking there may be a way to have it run cell 2 in a fragmented manner where each prime productp
is run independently, spits out a true or false for whether it creates a twin prime, then checks the next. Perhaps then a memory limit can be set on each individual fragment? $\endgroup$