fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6.  
  7. // Function to compute factorial modulo M
  8. ll factorial_mod(ll n, ll M) {
  9. ll res = 1;
  10. for (ll i = 2; i <= n; ++i)
  11. res = (res * i) % M;
  12. return res;
  13. }
  14.  
  15. // Function to compute power modulo M
  16. ll power_mod(ll base, ll exponent, ll M) {
  17. ll result = 1;
  18. base = base % M;
  19. while (exponent > 0) {
  20. if (exponent % 2 == 1)
  21. result = (result * base) % M;
  22. base = (base * base) % M;
  23. exponent = exponent / 2;
  24. }
  25. return result;
  26. }
  27.  
  28. // Function to compute modular inverse using Fermat's Little Theorem
  29. ll mod_inverse(ll a, ll M) {
  30. return power_mod(a, M - 2, M);
  31. }
  32.  
  33. int main() {
  34. ll N, M;
  35. cin >> N >> M;
  36.  
  37. ll N_factorial = factorial_mod(N, M);
  38. cout<<N_factorial<<endl;
  39. ll numerator = (N_factorial * ((N * N - 1) % M)) % M;
  40. ll denominator = (4 * N) % M;
  41.  
  42. // Compute modular inverse of denominator
  43. ll denom_inv = mod_inverse(denominator, M);
  44.  
  45. ll S = (numerator * denom_inv) % M;
  46.  
  47. cout << S << endl;
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0.01s 5292KB
stdin
3 107
stdout
6
4