Chinaunix首页 | 论坛 | 博客
  • 博客访问: 516181
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类: C/C++

2008-11-25 19:49:04


三种方式来实现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;
}

阅读(1345) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~