0
$\begingroup$

i know there is a Command in Matematica to get prime number, but i want to break down the code,here is what i got

Clear[a, b, n] a=For[n = 2, n <= 19, If[Mod[n, 2] < 1 , , Print[n]], n++]; b=For[n = 2, n <= 19, If[Mod[n, 3] < 1 , , Print[n]], n++]; Slice[a, b] 

and the result is 3 5 7 9 11 13 15 17 19 4 5 7 8 10 11 13 14 16 17 19 20

i want to slice it but i dont know how i want the result be 5 7 11 13 17 19

$\endgroup$
1
  • 1
    $\begingroup$ Prime[Range[10]] == Rest[Cases[FactorInteger[Range[30]], x_?(Length[#] == 1 && #[[1, 2]] == 1 &) :> x[[1, 1]]]] $\endgroup$ Commented May 3, 2018 at 5:11

2 Answers 2

1
$\begingroup$

Do you mean Intersection? The problem here is that with For, you get return value Null for both a and b. And of course Slice is not a Mathematica command. Try this instead:

Select[ Select[Range[2, 19], ! Divisible[#, 2] &], ! Divisible[#, 3] & ] 

Or this:

Intersection[ Pick[Range[2, 19], Divisible[Range[2, 19], 2], False], Pick[Range[2, 19], Divisible[Range[2, 19], 3], False] ] 

Or this:

Pick[ Range[2, 19], Times @@ Table[ Unitize[Mod[Range[2, 19], k]], {k, 2, 3} ], 1 ] 
$\endgroup$
2
$\begingroup$

The version of Mathematica I have do not have Slice command and never seen this in Mathematica? But assuming you want to capture the output in separate lists, you can try

Clear[a,b,n] a=Flatten@Rest@Reap@For[n=2,n<=19, If[Mod[n,2]<1, , Sow@n ], n++ ]; b=Flatten@Rest@Reap@For[n=2,n<=19, If[Mod[n,3]<1, , Sow@n ], n++ ]; 

And now

{a, b} 

gives

{{3,5,7,9,11,13,15,17,19},{4,5,7,8,10,11,13,14,16,17,19,20}} 

There are much better ways to do this. You can replace For by Do for example, and you can do all of this in a more functional way in Mathematica. But this is for another topic.

ps. Based on edit, you can now just do

 Intersection[a, b] 

which gives

 {5, 7, 11, 13, 17, 19} 
$\endgroup$
1
  • $\begingroup$ i already edit my question, i hope you understand $\endgroup$ Commented May 3, 2018 at 4:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.