使用C語言求N的階乘的方法
用遞歸法求N的階乘
程序調(diào)用自身稱為遞歸( recursion).它通常把一個大型復(fù)雜的問題層層轉(zhuǎn)化為一個與原問題相似的規(guī)模較小的問題來求解.
遞歸的能力在于用有限的語句來定義對象的無限集合。
一般來說,遞歸需要有邊界條件、遞歸前進段和遞歸返回段。當邊界條件不滿足時,遞歸前進;當邊界條件滿足時,遞歸返回。
#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!!\n");
return -1;
}
n = atoi(argv[1]);
printf("%d! = %ld\n",n,factorial(n));
return 0;
}
習題示例
題目
題目描述:
輸入一個正整數(shù)N,輸出N的階乘。
輸入:
正整數(shù)N(0<=N<=1000)
輸出:
輸入可能包括多組數(shù)據(jù),對于每一組輸入數(shù)據(jù),輸出N的階乘
樣例輸入:
4
5
15
樣例輸出:
24
120
1307674368000
AC代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 3000
//存儲每次階乘運算的結(jié)果
int str[MAX];
void calculateFactorial(int n);
int main()
{
int n;
while (scanf("%d", &n) != EOF) {
if(n == 0) {
printf("1\n");
} 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 ++) { //循環(huán)與2,3,..n相乘
for (j = 1, c = 0; j <= len; j ++) { //str數(shù)組代表一個數(shù),模擬與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("\n");
}
/**************************************************************
Problem: 1076
User: wangzhengyi
Language: C
Result: Accepted
Time:2150 ms
Memory:916 kb
****************************************************************/
相關(guān)文章
C++中main函數(shù)怎樣調(diào)用類內(nèi)函數(shù)
這篇文章主要介紹了C++中main函數(shù)怎樣調(diào)用類內(nèi)函數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
淺析C/C++中動態(tài)鏈接庫的創(chuàng)建和調(diào)用
下面小編就為大家?guī)硪黄獪\析C/C++中動態(tài)鏈接庫的創(chuàng)建和調(diào)用。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考,一起跟隨小編過來看看吧2016-05-05

