381 prime-k factorial -- v2.pl 812 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 21 August 2016
  5. # Website: https://github.com/trizen
  6. # https://projecteuler.net/problem=381
  7. # Runtime: 2.691s
  8. # Based on the following relations:
  9. #
  10. # (p-1)! mod p = p-1
  11. # (p-2)! mod p = 1
  12. # (p-3)! mod p = (p-1)/2
  13. # (p-5)! mod p = (p^2 -1)/24
  14. #
  15. # (p-4)! mod p has two paths:
  16. #
  17. # If (p+1) is divisible by 6, then: (p-4)! mod p = (p+1)/6
  18. # If (p+1) is not divisible by 6, then: (p-4)! mod p = p-floor(p/6)
  19. use 5.010;
  20. use strict;
  21. use integer;
  22. use ntheory qw(forprimes);
  23. sub S {
  24. my ($p) = @_;
  25. ( 1
  26. + ($p - 1)
  27. + (($p - 1) / 2)
  28. + (($p + 1) % 6 == 0 ? ($p + 1) / 6 : $p - ($p / 6))
  29. + (($p*$p - 1) / 24)
  30. ) % $p;
  31. }
  32. my $sum = 0;
  33. forprimes { $sum += S($_) } 5, 10**8;
  34. say $sum;