I have two lists of integers. The first, p, is a list of primes (for example, {2,3,5,7}). The second is a list t of three arbitrary integers (positive, negative, or zero), for example {10,15,24}. You are guaranteed at the outset that each element of t is prime to at least one element of p. I want to produce a list s having the same length as p, where each element of s comes from t (repetitions allowed) and such that CoprimeQ[s[[i]],p[[i]]] is True for each i. So in the above example {15,10,24,15} and {15,10,24,24} would both be acceptable answers.

I can produce a matrix that expresses whether each element of t is prime to each element of p using

Table[CoprimeQ[i, p], {i, t}]

but I don't see how to proceed efficiently from there. Or perhaps there's a better way altogether.


1 Answer 1


Try this:

p = {2, 3, 5, 7};
t = {10, 15, 24};
sol = Flatten[
  Table[RandomSample[Select[t, CoprimeQ[p[[i]], #] &], 1], {i, 1, 4}]];

CoprimeQ[p[[#]], sol[[#]]] & /@ Range[4]

(*{True, True, True, True}*)
  • $\begingroup$ Yes, I guess that's much easier than the complicated scheme I was cooking up. Thanks. $\endgroup$
    – rogerl
    Commented Nov 13, 2014 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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