1
$\begingroup$

I'm looking for a code that finds the number of primes p less than or equal to X satisfying p is congruent to 1 (mod 4) and another code that finds the number of primes p less than or equal to X satisfying p is congruent to 3 (mod 4).

$\endgroup$

2 Answers 2

3
$\begingroup$

Define a function that takes in a range and a criterion function.

fPrime[X_?NumericQ, f_Function] := {Length@#, #} &@
  Table[If[f@Prime[i], Prime[i], Nothing], {i, PrimePi[X]}]

Usage

fPrime[100, Mod[#, 4] == 1 &]

{11, {5, 13, 17, 29, 37, 41, 53, 61, 73, 89, 97}}

fPrime[100, Mod[#, 4] == 3 &]

{13, {3, 7, 11, 19, 23, 31, 43, 47, 59, 67, 71, 79, 83}}

$\endgroup$
3
  • $\begingroup$ I’m trying to find the number of primes in a large interval. It seems like what you’re providing is going to give me a set of primes and not the count. $\endgroup$
    – Karam
    Oct 16, 2022 at 16:38
  • $\begingroup$ It is providing you with both and you can choose to drop what you don't need. $\endgroup$
    – Syed
    Oct 16, 2022 at 16:39
  • $\begingroup$ Got it. Thanks! $\endgroup$
    – Karam
    Oct 16, 2022 at 17:13
3
$\begingroup$
Select[Range[100],And[PrimeQ[#],Mod[#,4]==1]&]
(* {5,13,17,29,37,41,53,61,73,89,97} *)

Select[Range[100],And[PrimeQ[#],Mod[#,4]==3]&]
(* {3,7,11,19,23,31,43,47,59,67,71,79,83} *)
$\endgroup$
4
  • $\begingroup$ One can observe that PrimePi4m1[x]+PrimePi4m3[x]+1==PrimePi[x]. This is the first step to make it more efficient. Another step would be harnessing PrimePi in a more extended way, something like it was done here. $\endgroup$
    – Artes
    Oct 16, 2022 at 13:34
  • $\begingroup$ Thank you. This code is really just a translation of an English sentence into Mathematica (more or less). There is certainly room for improvement if efficiency is a concern. $\endgroup$
    – user293787
    Oct 16, 2022 at 13:59
  • $\begingroup$ I’m not sure how to make this code work since it’s giving me the primes and not the number of primes. $\endgroup$
    – Karam
    Oct 16, 2022 at 16:36
  • 1
    $\begingroup$ You can apply Length to the result. $\endgroup$
    – user293787
    Oct 16, 2022 at 16:43

Your Answer

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

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