Algorithm
[BOJ 10872] 팩토리얼
승우승
2019. 7. 3. 09:41
반응형
문제출처
https://www.acmicpc.net/problem/10872
소스코드
첫번째 바로 푼 방법이데 재귀를 이용하여 풀었는데 당연히 시간초과가 났다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int fac(int n) { if (n==1) { return 1; } return n*fac(n-1); } int main(int argc, char** argv) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin>>n; cout<<fac(n); return 0; } | cs |
이후 일반적인 반복문으로 풀이하였다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> using namespace std; int main(int argc, char** argv) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, ans=1; cin>>n; for (int i=1; i<=n; i++) { ans *= i; } cout<<ans; return 0; } | cs |
반응형