2

I try to use the for loop to solve this question, but it does not work. And here is what I did.

For[p = 2,p<=10000,(p-1)! = -1 mod (p^2),Print[p]]

I am not sure how to describe "(p−1)!≡−1 mod p^2" in Mathematica. Could you give me some suggestions? Thank you.

User796
  • 47
  • 5

2 Answers2

6

It's probably faster to do a divisibility test than actually calculate the modulus:

Do[If[PrimeQ[p] && Divisible[(p - 1)! + 1, p^2], Sow[p]], {p, 10^4}] // Reap // Last

(* {{5, 13, 563}} *)

For is poor style in Mathematica. Use Do or Table instead.

Print is only useful if you want to read the results from the screen. If you want to use the results in further calculations, a Sow/Reap combination is preferrable: Collecting Expressions during Evaluation.

Roman
  • 47,322
  • 2
  • 55
  • 121
5
Select[Range[10000], Mod[(# - 1)! + 1, #^2] == 0 &]

But I think we should test only the prime number,so we modified the above code.

Select[Prime[Range[10000]], Mod[(# - 1)! + 1, #^2] == 0 &]
(* {5, 13, 563} *)
cvgmt
  • 72,231
  • 4
  • 75
  • 133