[演算法C語言描述]大數、巨數的階乘演算法

來源:互聯網
上載者:User

用數組的方法解決大數、巨數的階乘結果越界的問題。

具體演算法中有最樸實的乘法運算思想,請各位細細體味。

#include <stdio.h>

int main()
{
 
 int n;                                            //階乘大小
 printf("請輸入n的大小:");
 scanf("%d",&n);                                   //從鍵盤接收階乘大小
 int a[200];                                       //確保儲存最終運算結果的數組足夠大
 int carry;                                        //進位
 int digit = 1;                                    //位元
 a[0] = 1;                                         //將結果先初始化為1
 int temp;                                         //階乘的任一元素與臨時結果的某位的乘積結果
        
 for(int i = 2; i <= n; ++i)                       //開始階乘,階乘元素從2開始依次“登場”
 {
         //按最基本的乘法運算思想來考慮,將臨時結果的每位與階乘元素相乘 
  for(int j = 1, carry = 0; j <= digit; ++j)   
  {
   temp = a[j-1] * i + carry;                //相應階乘中的一項與當前所得臨時結果的某位相乘(加上進位)
        a[j-1] = temp % 10;                       //更新臨時結果的位上資訊
   carry = temp / 10;                        //看是否有進位
  }
  while(carry)                                  //如果有進位
  {
   a[++digit-1] = carry % 10;                //新加一位,添加資訊。位元增1
   carry /= 10;                              //看還能不能進位
  }
 }

 printf("結果是:/n%d ! = ",n);                     //顯示結果
 for(int i = digit; i >=1; --i)
 {
  printf("%d",a[i-1]);
 }
 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.