我只能说太狗了,竟然忘记了0!=1,导致wa了好几次。
有两大种方法:
1.用数组
一开始我还以为我思路有问题,换了好几种思路,结果都还是wa,在知道是错在0!的时候。。。我直接原地去世呜呜
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e3+7; ll a[20]; void inif(){ a[0]=1; a[1]=1; // for(int i = 1; i <= 20; ++i) a[i] = 1; for(int i = 2; i <= 20; ++i){ a[i] = a[i-1]*i; // for(int j = 1; j <= i; ++j){ // a[i] *= j; // } } return ; } int main(){ int t, n; inif(); cin >> t; while(t--) { cin >> n; // int ans=1; // for (int i = 1; i <= n; ++i){ // ans *= i; // } cout << a[n] << endl; } return 0; }
2.dfs
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e3+7; ll dfs(int n){ if(n==0) return 1; else return dfs(n-1)*n; } int main(){ int t, n; cin >> t; while(t--) { cin >> n; cout << dfs(n) << endl; } return 0; }