fork download
  1. /**
  2.  * author: orzvanh14 ( )
  3.  * created: 19.06.2026 19:15:02
  4. **/
  5. #include <bits/stdc++.h>
  6.  
  7. using namespace std;
  8.  
  9. #define int long long
  10. #define nn "\n"
  11.  
  12. const int mod = 1e9 + 7;
  13. const int N = 1e5 + 5;
  14. int D[N];
  15.  
  16. void solve(){
  17. int n;
  18. cin >> n;
  19.  
  20. if (n == 1) {
  21. cout << 0 << nn;
  22. return;
  23. }
  24. if (n == 2) {
  25. cout << 1 << nn;
  26. return;
  27. }
  28.  
  29. D[1] = 0;
  30. D[2] = 1;
  31. for(int i = 3; i <= n; i++){
  32. // Công thức: D[n] = (n - 1) * (D[n-1] + D[n-2]) % mod
  33. D[i] = (i - 1) * (D[i - 1] + D[i - 2]) % mod;
  34. }
  35.  
  36. cout << D[n] << nn;
  37. }
  38.  
  39. signed main() {
  40. ios_base::sync_with_stdio(0);
  41. cin.tie(0);
  42. cout.tie(0);
  43. solve();
  44. return (0 ^ 0);
  45. }
Success #stdin #stdout 0s 5316KB
stdin
4
stdout
9