大数的阶乘
在计算机中,变量存储在内存位置。但内存位置的大小是固定的,所以当我们要找到一些更大值(例如 15!或 20!)的阶乘时,阶乘值将超出内存范围并返回错误结果。
对于大数的计算,我们必须使用数组来存储结果。在数组的每个元素中,都存储结果的不同位数。但这里我们无法直接将某些数字与数组相乘,我们必须对结果数组的所有位数执行手动乘法过程。
输入和输出
Input: A big number: 50 Output: Factorial of given number is: 30414093201713378043612608166064768844377641568960512000000000000
算法
multiply(x, multiplicand)
输入:数字 x,和作为数组的大乘数。
输出:相乘后的结果。
Begin carry := 0 for all digits i of multiplicand, do prod := i*x+carry i := prod mod 10 carry := prod / 10 done while carry ≠ 0, do insert (carry mod 10) at the end of multiplicand array carry := carry/10 done End
factorial(n)
输入:数字 n。
输出:求 n 的阶乘。
Begin define result array. insert 1 in the result for i := 2 to n, do multiply(i, result) done reverse the result return result End
范例
#include<iostream> #include<vector> #include<algorithm> using namespace std; void multiply(int x, vector<int>&multiplicand) { //multiply multiplicand with x int carry = 0; // Initialize carry to 0 vector<int>::iterator i; for (i=multiplicand.begin(); i!=multiplicand.end(); i++) { //multiply x with all digit of multiplicand int prod = (*i) * x + carry; *i = prod % 10; //put only the last digit of product carry = prod/10; //add remaining part with carry } while (carry) { //when carry is present multiplicand.push_back(carry%10); carry = carry/10; } } void factorial(int n) { vector<int> result; result.push_back(1); //at first store 1 as result for (int i=2; i<=n; i++) multiply(i, result); //multiply numbers 1*2*3*......*n cout << "Factorial of given number is: "<<endl; reverse(result.begin(), result.end()); vector<int>::iterator it; //reverse the order of result for(it = result.begin(); it != result.end(); it++) cout << *it; } int main() { factorial(50); }
输出
Factorial of given number is: 30414093201713378043612608166064768844377641568960512000000000000
广告