欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

使用C語言求N的階乘的方法

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點(diǎ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
    ****************************************************************/

上一篇:利用C語言來求最大連續(xù)子序列乘積的方法

欄    目:C語言

下一篇:C語言中的鏈接編寫教程

本文標(biāo)題:使用C語言求N的階乘的方法

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/2886.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有