使用C語言求N的階乘的方法
用遞歸法求N的階乘
程序調(diào)用自身稱為遞歸( recursion).它通常把一個大型復(fù)雜的問題層層轉(zhuǎn)化為一個與原問題相似的規(guī)模較小的問題來求解.
遞歸的能力在于用有限的語句來定義對象的無限集合。
一般來說,遞歸需要有邊界條件、遞歸前進(jìn)段和遞歸返回段。當(dāng)邊界條件不滿足時,遞歸前進(jìn);當(dāng)邊界條件滿足時,遞歸返回。
#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;
}
習(xí)題示例
題目
題目描述:
輸入一個正整數(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
//存儲每次階乘運(yùn)算的結(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)文章
Vscode搭建遠(yuǎn)程c開發(fā)環(huán)境的圖文教程
很久沒有寫C語言了,今天抽空學(xué)習(xí)下C語言知識,接下來通過本文給大家介紹Vscode搭建遠(yuǎn)程c開發(fā)環(huán)境的詳細(xì)步驟,本文通過圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-11-11
C++實(shí)現(xiàn)圖書管理系統(tǒng)最新版
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)圖書管理系統(tǒng)最新版,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06
C++實(shí)現(xiàn)LeetCode(29.兩數(shù)相除)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(29.兩數(shù)相除),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
LeetCode 單調(diào)棧內(nèi)容小結(jié)
這篇文章主要介紹了LeetCode 單調(diào)棧內(nèi)容小結(jié),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

