使用C语言求N的阶乘的方法是很多小伙伴都想知道的,下面小编给大家介绍如何使用C语言求N的阶乘,欢迎阅读!
如何使用C语言求N的阶乘用递归法求N的.阶乘
程序调用自身称为递归( recursion).它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解.
递归的能力在于用有限的语句来定义对象的无限集合。
一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
12345678910111213141516171819202122232425262728293031323334353637383940414243 | #include <stdio.h> #include <string.h> #include <stdlib.h> long factorial( int n) {
if (n == 1) return 1;
else return n*factorial(n-1); } int main( int argc, char *argv[]) {
int n = 0;
if (argc != 2)
{ printf ( "input error,exit!!" ); return -1;
}
n = atoi (argv[1]);
printf ( "%d! = %ld" ,n,factorial(n));
return 0; } |
习题示例
题目描述:
输入一个正整数N,输出N的阶乘。
输入:
正整数N(0<=N<=1000)
输出:
输入可能包括多组数据,对于每一组输入数据,输出N的阶乘
样例输入:
4
5
15
样例输出:
24
120
1307674368000
AC代码
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 | #include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAX 3000
//存储每次阶乘运算的结果 int str[MAX];
void calculateFactorial( int n);
int main() {
int n;
while ( scanf ( "%d" , &n) != EOF) { if (n == 0) { printf ( "1" ); } else { calculateFactorial(n); }
}
return 0; }
void calculateFactorial( int n) {
int i, j, temp, c, len;
memset (str, 0, sizeof (str));
str[1] = 1;
for (i = 2, len = 1; i <= n; i ++) { //循环与2,3,..n相乘 for (j = 1, c = 0; j <= len; j ++) { //str数组代表一个数,模拟与i相乘 temp = str[j] * i + c; str[j] = temp % 10; c = temp / 10; } while (c > 0) { str[j ++] = c % 10; c /= 10; } len = j - 1;
}
for (i = len; i >= 1; i --) { printf ( "%d" , str[i]);
}
printf ( "" ); } |
/**************************************************************
Problem: 1076
User: wangzhengyi
Language: C
Result: Accepted
Time:2150 ms
Memory:916 kb