九度OJ 1076 n的階乘

題目1076:N的階乘

時間限制:3 秒

內存限制:128 兆

特殊判題:

提交:8753

解決:3250

題目描述:

 輸入一個正整數N,輸出N的階乘。

輸入:

正整數N(0<=N<=1000)

輸出:

 輸入可能包括多組數據,對於每一組輸入數據,輸出N的階乘

樣例輸入:
4
5
15
樣例輸出:
24
120
1307674368000
來源:
2006年清華大學計算機研究生機試真題

解法&&思路:

一個個累乘,中間結果用字符數組保存,按位累乘,一位一位的更新字符數組


Code:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stdio.h>
#include <math.h>


#define MAXN 10000


int main() {
int n;
while (std::cin >> n) {
int a[MAXN], b[MAXN];
std::fill(a, a+MAXN, 0);
std::fill(b, b+MAXN, 0);
a[0] = 1;
int len = 1;
for (int i = 1; i <= n; i++) {
int c = 0;
for (int j = 0; j < len; j++) {
int temp = i*a[j] + c;
a[j] = temp % 10;
c = temp / 10;
}
while (c >= 10) {
a[len++] = c % 10;
c /= 10;
}
if (c > 0) {
a[len++] = c;
}
}
for (int i = len - 1; i >= 0; i--) {
printf("%d", a[i]);
}
printf("\n");
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章