计算任意大数的阶乘,显示所有数字 [英] Calculate the factorial of an arbitrarily large number, showing all the digits
问题描述
我最近在接受采访时询问,描述一种计算任意大数的阶乘的方法;
I was recently asked, in an interview, to describe a method to calculate the factorial of any arbitrarily large number; a method in which we obtain all the digits of the answer.
我搜索了多个地方,并在几个论坛中询问。但是我想知道如果没有使用GMP这样的库,有什么方法可以实现。
I searched various places and asked in a few forums. But I would like to know if there is any way to accomplish this without using libraries like GMP.
谢谢。
推荐答案
GNU多精度库是一个好的!但是因为你说使用外部库是不允许的,只有我相信它的可能是通过采取一个int数组,然后乘以数字,你用笔在纸上!
GNU Multiprecision library is a good one! But since you say using of external libraries are not allowed, only way I believe its possible is by taking an array of int and then multiplying numbers as you do with pen on paper!
这是我写了一段时间的代码。
Here is the code I wrote some time back..
#include<iostream>
#include<cstring>
int max = 5000;
void display(int arr[]){
int ctr = 0;
for (int i=0; i<max; i++){
if (!ctr && arr[i]) ctr = 1;
if(ctr)
std::cout<<arr[i];
}
}
void factorial(int arr[], int n){
if (!n) return;
int carry = 0;
for (int i=max-1; i>=0; --i){
arr[i] = (arr[i] * n) + carry;
carry = arr[i]/10;
arr[i] %= 10;
}
factorial(arr,n-1);
}
int main(){
int *arr = new int[max];
std::memset(arr,0,max*sizeof(int));
arr[max-1] = 1;
int num;
std::cout<<"Enter the number: ";
std::cin>>num;
std::cout<<"factorial of "<<num<<"is :\n";
factorial(arr,num);
display(arr);
delete[] arr;
return 0;
}
'arr'只是一个整数数组,阶乘是一个简单函数将给定数乘以大数。
'arr' is just an integer array, and factorial is a simple function that multiplies the given number to the 'large number'.
希望这解决了您的查询。
Hope this solves your query..
这篇关于计算任意大数的阶乘,显示所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!