三种方式来实现n的阶乘:循环、递归、非递归
虽然这么做看起来有点多此一举,不过对学习递归和非递归是很有好处的!
循环方式:
#include <stdio.h>
int main(int argc,char **argv)
{
int i,n;
int sum=1;
printf("Input a number:");
scanf("%d",&n);
if(n<0){
printf("Number must bigger than 0.\n");
exit(1);
}
for(i=1;i<=n;i++){
sum*=i;
}
printf("The result is:%d \n",sum);
return 0;
}
|
递归版
#include <stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return(factorial(n-1)*n);
}
int main(int argc,char **argv)
{
int n;
int sum;
printf("Input a number:");
scanf("%d",&n);
if(n<0){
printf("Number must larger than 0.\n");
exit(1);
}
sum=factorial(n);
printf("The factorial is:%d \n",sum);
return 0;
}
|
非递归版
#include <stdio.h>
#include <stdlib.h>
struct node{
int key;
struct node *next;
};
typedef struct node Node;
void push(Node **S,int i)
{
Node *temp;
temp=(Node *)malloc(sizeof(Node));
if(temp == NULL){
printf("Malloc error!\n");
exit(1);
}
temp->key=i;
temp->next=*S;
*S=temp;
}
void pop(Node **S,int *e)
{
Node *temp;
temp=*S;
*S=temp->next;
*e=temp->key;
temp->next=NULL;
free(temp);
temp=NULL;
}
int factorial(int n)
{
Node *S=NULL;
int i=n;
int e,rst=1;
while(i>0 || S){
if(i>0){
push(&S,i);
i--;
}
else{
pop(&S,&e);
rst*=e;
}
}
return rst;
}
int main(int argc,char **argv)
{
int n;
int result;
printf("Input a number:");
scanf("%d",&n);
if(n<0){
printf("Number must larger than 0.\n");
exit(1);
}
result=factorial(n);
printf("The factorial is:%d \n",result);
return 0;
}
|
阅读(1381) | 评论(0) | 转发(0) |