0
$\begingroup$

I want Mathematica code the does what the following pseudocode does.

s = 0
for i = 1 to x
  if i is a prime number then 
    s = s + 1, print s 
  else  
    print "unspecified"

I tried

numPrime1[n_] :=  
 Block[{i, j, g, s, f}, s = 0; f = 0; g = 0; 
  For[i = 1, i <= n, i++,               
    For[j = 1, j <= i, j++,
      If[OddQ[i/j], f = f + 1]
      ]
     If[f == 2, s = s + 1, break]               
     If[OddQ[n/i], g = g + 1;]
    ]
   If[g == 2, Print[s], Print["Ungültig"];]]
numPrime1[17]

Now that just returns Null^3

Edit 1

Now it returns 1, but I don't know why it shouldn't be 1. Can someone give me advice to make that work?

Edit 2

Solved it now this way

numPrime1[n_] := Block[{i, j, g, s, f}, s = 0; f = 0; g = 0;
  For[i = 1, i <= n, i++,
   For[j = 1, j <= i, j++,
     If[IntegerQ[i/j], f = f + 1];] 
    If[f == 2, s = s + 1]; 
   If[IntegerQ[n/i], g = g + 1];
   f = 0]; 
  If[g == 2, Print[s], Print["Ungültig"]];]
numPrime1[17]

All my tests are now correct.

$\endgroup$
2
  • 3
    $\begingroup$ It appears you are after PrimePi. Check details in documentation. $\endgroup$
    – ciao
    Commented Nov 9, 2019 at 19:55
  • $\begingroup$ I want to calculate it this way so i don't have to use that $\endgroup$
    – Rack Cloud
    Commented Nov 9, 2019 at 20:37

1 Answer 1

5
$\begingroup$

Mathematica has a lot of prime functionality built in. In particular PrimeQ[x] gives True if x is prime and false otherwise, and PrimePi[x] counts the number of primes less than or equal to x.

So, it seems like you want something like

numPrime[n_] := If[PrimeQ[n], PrimePi[n], Null]

so that numPrime[17]=7 and numPrime[21] is Null (or you could print something, throw an error, etc.)

$\endgroup$
0

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.