曾彪彪的个人网站
首页
文章列表
>>
文章详情
不用循环求阶层(有意思)
作者:
曾彪彪
日期:
2025-06-20 05:15:45
阅读(78)
分类:
Algorithm
# P5739 【深基7.例7】计算阶乘 ## 题目描述 求 $n!$,也就是 $1\times2\times3\dots\times n$。 挑战:尝试不使用循环语句(for、while)完成这个任务。 ## 输入格式 第一行输入一个正整数 $n$。 ## 输出格式 输出一个正整数,表示 $n!$。 ## 输入输出样例 #1 ### 输入 #1 ``` 3 ``` ### 输出 #1 ``` 6 ``` ## 说明/提示 数据保证,$1 \leq n\le12$。 我的解法:记忆递归 ``` c++ /** start time: 13:00 End time: Solution: - memorized recursive - define an array to store the result of n - test case: - 1 - 3 - 5 - 10 - 12 first submit score: 100 cause: **/ #include <bits/stdc++.h> using namespace std; long long factorial(long long n, vector<long long> &ans) { if (n == 1) { ans[0] == 1; return 1; } if (ans[n] > 0) { return ans[n]; } long long r = factorial(n - 1, ans) * n; ans[n] = r; return r; } int main() { long long n; cin >> n; vector<long long> ans(n + 1, 0); cout << factorial(n, ans); return 0; } ``` 高手解法,正向计算 ``` c++ #include<cstdio> #include<algorithm> #include<iostream> #define FOR(I, A, N) for(int I = A; I <= N; I++)//秀一下我的C++技术(说明我很水 #define For(I, A, N) for(int I = A; I >= N; I--)//在秀一波 #define LL long long//三年OI一场梦 不开long long见祖宗,(不知我背的对不对?) using namespace std; long long ans = 1; int n; void jie_cheng(int x)//递归 { ans *= x; if(x == n) { return; } jie_cheng(x + 1); } int main() { scanf("%d", &n); jie_cheng(1);//从1开始,一直到n printf("%lld\n", ans);输出不多说 return 0; } ``` 神仙解法 ``` c++ #include<cstdio> #include<iostream> #include<algorithm> using namespace std; int ans[13]={1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600}; int main(){ int n; cin>>n; cout<<ans[n]; return 0; } ```
评论(0)
评论(必填)
名称(必填)
联系方式(可选)
验证码(必填)
提交
评论(必填)
名称(必填)
联系方式(可选)
验证码(必填)