69,774
社区成员
发帖
与我相关
我的任务
分享
老赵的千年老代码还是有些价值的~
仅供参考:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
inline int COMPARE(string str1,string str2) {//相等返回0,大于返回1,小于返回-1
if (str1.size()>str2.size()) return 1; //长度长的整数大于长度小的整数
else if (str1.size()<str2.size()) return -1;
else return str1.compare(str2); //若长度相等,则头到尾按位比较
}
string PLUS(string number1,string number2) {
int i;
int length1 = number1.size();
int length2 = number2.size();
string result="";
reverse(number1.begin(), number1.end());
reverse(number2.begin(), number2.end());
for(i = 0; i < length1 && i < length2; i++) {
char c = (char)(number1[i] + number2[i] - 48);
result = result + c;
}
while(i < length1) {
result = result + number1[i];
++i;
}
while(i < length2) {
result = result + number2[i];
++i;
}
int carry = 0;
for(i = 0; i < (int)result.size(); ++i) {
int value = result[i] - 48 + carry;
result[i] = (char)(value % 10 + 48);
carry = value / 10;
}
if(carry !=0 ) {
result = result + (char)(carry + 48);
}
for(i = result.size() - 1; i >= 0; i--) {
if(result[i] != '0') break;
}
result = result.substr(0, i + 1);
reverse(result.begin(), result.end());
if(result.length() == 0) result = "0";
return result;
}
string MULTIPLY(string number1, string number2) {
int i, j;
int *iresult;
int length1 = number1.size();
int length2 = number2.size();
string result = "";
reverse(number1.begin(), number1.end());
reverse(number2.begin(), number2.end());
iresult = (int*)malloc(sizeof(int) * (length1 + length2 + 1));
memset(iresult, 0, sizeof(int) * (length1 + length2 + 1));
for(i = 0; i < length1; i++) {
for(j = 0; j < length2; j++) {
iresult[i+j] += ((number1[i] - 48) * (number2[j] - 48));
}
}
int carry = 0;
for(i = 0; i < length1 + length2; i++) {
int value = iresult[i] + carry;
iresult[i] = value % 10;
carry = value / 10;
}
for(i = length1 + length2 - 1; i >= 0; i--) {
if(iresult[i] != 0)break;
}
for(; i >= 0; i--) {
result = result + (char)(iresult[i]+48);
}
free(iresult);
if(result == "") result = "0";
return result;
}
string factorial(string n) {
string temp = "1";
string i;
for(i = "1"; COMPARE(i, n) <= 0; i = PLUS(i, "1")) {
temp = MULTIPLY(temp, i);
}
return temp;
}
int main(void) {
cout << factorial("100") << endl;
return 0;
}
//93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
//
题干的前六个字“用高精度计算”。
这意味着任何内置的数据类型都不足以正确表达题目中需要的数值,您需要用数组保存完整的数据,并自行实现基于数组的加法和阶乘运算函数。
50的阶乘是30414093201713378043612608166064768844377641568960512000000000000 ,
long long放不下的。