计算任意数字的阶乘,显示所有数字

最近有人在一次采访中要求我描述一种计算任意大数的阶乘的方法。一种获取答案的所有数字的方法。

我搜索了多个地方,并在几个论坛中询问。但是我想知道是否有任何方法可以在不使用GMP之类的库的情况下完成此任务。


慕后森
浏览 420回答 3
3回答

宝慕林4294392

GNU Multiprecision库是一个很好的库!但是由于您说不允许使用外部库,所以我认为唯一可能的方法是采用一个int数组,然后像用笔在纸上一样将数字相乘!这是我前一段时间写的代码。#include<iostream>#include<cstring>int max = 5000;void display(int arr[]){&nbsp; &nbsp; int ctr = 0;&nbsp; &nbsp; for (int i=0; i<max; i++){&nbsp; &nbsp; &nbsp; &nbsp; if (!ctr && arr[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ctr = 1;&nbsp; &nbsp; &nbsp; &nbsp; if(ctr)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cout<<arr[i];&nbsp; &nbsp; }}void factorial(int arr[], int n){&nbsp; &nbsp; if (!n) return;&nbsp; &nbsp; int carry = 0;&nbsp; &nbsp; for (int i=max-1; i>=0; --i){&nbsp; &nbsp; &nbsp; &nbsp; arr[i] = (arr[i] * n) + carry;&nbsp; &nbsp; &nbsp; &nbsp; carry = arr[i]/10;&nbsp; &nbsp; &nbsp; &nbsp; arr[i] %= 10;&nbsp; &nbsp; }&nbsp; &nbsp; factorial(arr,n-1);}int main(){&nbsp; &nbsp; int *arr = new int[max];&nbsp; &nbsp; std::memset(arr,0,max*sizeof(int));&nbsp; &nbsp; arr[max-1] = 1;&nbsp; &nbsp; int num;&nbsp; &nbsp; std::cout<<"Enter the number: ";&nbsp; &nbsp; std::cin>>num;&nbsp; &nbsp; std::cout<<"factorial of "<<num<<"is :\n";&nbsp; &nbsp; factorial(arr,num);&nbsp; &nbsp; display(arr);&nbsp; &nbsp; delete[] arr;&nbsp; &nbsp; return 0;}“ arr”只是一个整数数组,阶乘是一个简单的函数,会将给定的数字乘以“大数”。希望这能解决您的查询。
打开App,查看更多内容
随时随地看视频慕课网APP