大數問題:求n的階乘,大數求n階乘
題目:求100!
這看起來是一個很簡答的問題,遞迴解之毫無壓力
int func(int n){ if(n <= 1) return 1; else return n*func(n-1);}但你會發現,題目真的有這麼簡單嗎,考慮整形資料越界沒有?
這實際上是一個大數問題!
大數怎麼表示呢,很直接的,我們會想到用字串來表示,但表示的過程中還得做階乘運算,是不是想象的那麼複雜呢?
其實,用基本的乘法運算思想(從個位到高位逐位相乘,進位)來考慮,將臨時結果的每位與階乘元素相乘,向高位進位,問題並不是那麼複雜。
代碼中注釋很詳細,不多說,直接貼在下面了。
public static void main(String[] args) throws IOException {int digit = 1; // 位元int temp; // 階乘的任一元素與臨時結果的某位的乘積結果int i, j, carry; // 進位boolean isnavigate = false;// 輸入的數是正數還是負數int[] a = new int[3000]; // 確保儲存最終運算結果的數組足夠大System.out.println("請輸入一個數字,求它的階乘");String nStr = ClassicalIOCode.getSystemInput();int n = 1;try {n = Integer.parseInt(nStr);}catch(NumberFormatException nfe) {System.out.println("請輸入合法的正整數!");return;}if(n < 0) {n = -n;isnavigate = true;}a[0] = 1; // 將結果先初始化為1for (i = 2; i <= n; i++) { // 開始階乘,階乘元素從2開始依次"登場"// 按最基本的乘法運算思想(從個位到高位逐位相乘,進位)來考慮,將臨時結果的每位與階乘元素相乘for (j = 1, carry = 0; j <= digit; j++) { // carry:進位temp = a[j - 1] * i + carry; // 相應階乘中的一項與當前所得臨時結果的某位//相乘(加上進位)a[j - 1] = temp % 10; // 更新臨時結果的位上資訊carry = temp / 10; // 看是否有進位}while (carry != 0) { // 如果有進位a[++digit - 1] = carry % 10; // 新加一位,添加資訊。位元增1carry = carry / 10; // 看還能不能進位}}if(isnavigate) {if(n % 2 == 1) {System.out.print((-n) + "的階乘:"+ (-n) +"! = -"); // 顯示結果}else {System.out.print((-n) + "的階乘:"+ (-n) +"! = "); // 顯示結果}}else {System.out.print(n + "的階乘:"+ n +"! = "); // 顯示結果}for (j = digit; j >= 1; j--) {System.out.print(a[j - 1]);}System.out.println();}
編寫一個程式,可以一個大數n的階乘(n),n的值範圍從1—100之間的變化
求大數階乘的經典演算法早就有了,下面是按你要求改動過的,希望對你有協助:
#include <stdio.h>
int main()
{
int n;
int k;
int a[9000]; //確保儲存最終運算結果的數組足夠大
int digit = 1; //位元
int temp; //階乘的任一元素與臨時結果的某位的乘積結果
int i,j,carry; //進位
printf("please in put n:\n");
scanf("%d",&n);
a[0] = 1; //將結果先初始化為1
for(i = 2; i <= n; i++) { //開始階乘,階乘元素從2開始依次"登場"
//按最基本的乘法運算思想來考慮,將臨時結果的每位與階乘元素相乘
for( j = 1, carry = 0; j <= digit; j++) { //carry:進位
temp = a[j-1] * i + carry; //相應階乘中的一項與當前所得臨時結果的某位//相乘(加上進位)
a[j-1] = temp % 10; //更新臨時結果的位上資訊
carry = temp / 10; //看是否有進位
}
while(carry) { //如果有進位
a[++digit-1] = carry % 10; //新加一位,添加資訊。位元增1
carry = carry/10; //看還能不能進位
}
}
printf("n ! = "); //顯示結果
k=0;
for(j = digit; j >=1;j--) {
if k=3
{
printf(",");
k=0;
}
else
k++;
printf("%d",a[j-1]);
}
printf("\n");
return 0;
}
編寫一個C++程式,可以一個大數n的階乘(n!),n的值範圍從1100之間變化
#include <iostream>
#include <vector>
using namespace std;
#define MAX_DIGITAL 10000
void PrintFactorial(unsigned int n)
{
vector<unsigned int> r(1, 1);
size_t j = 0;
for (unsigned int i = 1; i <= n; i++)
{
for (j = 0; j < r.size(); j++)
{
r[j] *= i;
}
int carry = 0;
j = 0;
do
{
r[j] += carry;
carry = r[j] / MAX_DIGITAL;
r[j] %= MAX_DIGITAL;
} while (++j < r.size());
if (carry > 0)
{
r.push_back(carry);
}
}
cout << *r.rbegin();
for_each(++r.rbegin(), r.rend(), [](const long val){
printf_s(",%04d", val);
});
}
int main(int argc, _TCHAR* argv[])
{
PrintFactorial(100);
cout << endl;
system("pause");
return 0;
}