# How to generate primes of the form 8n+1?

I'm trying to extract from the list of the first one hundred primes those which have the form 8n+1. I have tried using Select but this just gives me an empty list:

Select[Table[Prime[n], {n, 1, 100}] , Mod[n, 8] == 1]


I have also tried using Array but this crashes every time:

Select[Array[Prime, Prime[Range]], Mod[#, 8] == 1 &]


The following code works but this is not quite what I'm looking for:

Select[Array[Prime, PrimePi], Mod[#, 8] == 1 &]

• Select[Table[Prime[n], {n, 1, 100}], Mod[#, 8] == 1 &] I'm not sure but maby this – David Baghdasaryan May 11 '17 at 17:17
• Pick[#, Mod[#, 8], 1] &@Prime@Range@100 – Michael E2 May 11 '17 at 17:53
• you can also reverse the process as : Select[8 Range + 1, PrimeQ] – george2079 May 11 '17 at 20:33

I'll comment on why your initial attempts failed and attempt to correct them. Others have done a better job suggesting better approaches.

(* Fails -- second argument of Select needs to be a function *)
Select[Table[Prime[n], {n, 1, 100}] , Mod[n, 8] == 1]


In the first argument, you generated a list of the first 100 primes (as desired). But the second argument of Select needs to be a function. As David Baghdasaryan noted in the comments and David G Stork cleaned abbreviated in his answer, simply making the second argument a pure function works:

(* Works -- as suggested by David G Stork *)
Select[Prime[Range], Mod[#,8] == 1&]


(* Fails -- list of primes constructed improperly *)
Select[Array[Prime, Prime[Range]], Mod[#, 8] == 1 &]


This correctly passes a function in the second argument, but the list of primes is constructed improperly. Actually, if you replaced Array with Table, this would have worked, but Array has different syntax. The second argument of Array always specifies the length of the list. You passed a list of the first 100 primes, so Array attempted to construct a list with 100 nestings.

Actually, it would be fairly terse to write

(* Works *)
Select[Array[Prime, 100], Mod[#, 8] == 1 &]


which works similarly to David G Stork's method with marginally fewer characters.

(* Partially succeeds-- list of primes only partially constructed *)
Select[Array[Prime, PrimePi], Mod[#, 8] == 1 &]


PrimePi returns the number of primes less than, which is 25, so this method is equivalent to writing Select[Array[Prime, 25], Mod[#, 8] == 1 &]. As you noted, this is not what you want.

Inefficient, but works:

Intersection[
Table[8 n + 1, {n, Round[Prime/8]}], Prime[Range]
]


and a shorter implementation of David Baghdasaryan's solution:

Select[Prime@Range@100, Mod[#,8] == 1&]


I prefer @jjc385's explanatory answer, but here are some ways to consider:

Prime[Range] // Pick[#, Mod[#, 8], 1] &

Cases[Prime[Range], p_ /; Mod[p, 8] == 1]

Select[Prime[Range], Mod[#, 8] == 1 &]

Solve[p <= Prime && Mod[p, 8] == 1, p, Primes]

Solve[p <= Prime && p == 8 n + 1 && p ∈ Primes && n ∈ Integers, {p, n}]