蓝桥杯 - 基础练习 阶乘计算(计算超时,用的string)
问题描述 输入一个正整数n,输出n!的值。 其中n!=1*2*3*…*n。 算法描述 n!可能很大,而计算机能表示的整数范围有限,需要使用高精度计算的方法。使用一个数组A来表示一个大整数a,A[0]表示a的个位,A[1]表示a的十位,依次类推。 将a乘以一个整数k变为将数组A的每一个元素都乘以k,请注意处理相应的进位。 首先将a设为1,然后乘2,乘3,当乘到n时,即得到了n!的值。 输入格式 输入包含一个正整数n,n<=1000。 输出格式 输出n!的准确值。 样例输入 10 样例输出 3628800
#include "string.h" #include "stdlib.h" #include "stdio.h" #include "sstream" #include "iostream" using namespace std; string zsTost(int a) { stringstream ss; string aa; ss << a; ss >> aa; return aa; } int stTozs(string a) { stringstream ss; int aa; ss << a; ss >> aa; return aa; } string AddWtoSmall(string s1, string s2) { //cout << "ru" << s1 << "+" << s2<<endl; string s3=""; stringstream ss1, ss2,ss3,ss0; string s0=""; int jw = 0; int cd0,cd1, cd2,cdx; cd1 = s1.length(); cd2 = s2.length(); int shiyong=1; if (cd1 >= cd2) { cd0 = cd1; cdx = cd2; shiyong = 1; //cout << "qqqqq1111"; } else { cdx = cd1; cd0 = cd2; shiyong = 2; } int dp; for (int i = 0; i < cd0; i++) { if (i >= cdx ) { if (i <= cd0) { if (shiyong == 1) { //cout << cd1 - i - 1 << "cd1 - i - 1" << endl; dp = s1[cd1 - i - 1] - '0'; //cout << dp<<"shiyong1" << endl; } else { dp = s2[cd2 - i - 1] - '0'; //cout << dp << "shiyong2" << endl; } } } else { dp = s1[cd1 - i - 1] - '0' + s2[cd2 - i - 1] - '0'; } s3 = ""; dp += jw; //cout << jw << "jw" << endl; //cout << s0 << endl; if (dp>=10) { dp -= 10; jw = 1; } else { jw = 0; } s3 = zsTost(dp); s0 = s3 + s0; } if (jw==1) { s3 = zsTost(jw); s0 = s3+s0; } //cout << s0 << endl; return s0; } int main() { //cout << AddWtoSmall("1", "12") << endl; int n = 0; cin >> n; n +=1 ; int cd; string A="1"; int ls1; string sls1; stringstream ss[1000]; string sz="0"; for (int i = 2; i <n; i++) { cd = A.length(); sz = "0"; //cout << A << endl; for (int i1 = 0; i1 < cd; i1++) { ls1 = (A[cd-i1-1]-'0') * i; //cout << ls1 << endl; sls1 = zsTost(ls1); for (int i2 = 0; i2 < i1; i2++) { if (ls1!=0) { sls1 = sls1 + "0"; } } //cout << sz << "szquab" << sls1 << endl; //cout << "sssssss" << sls1 << endl; sz = AddWtoSmall(sz, sls1); //cout <<"xiangcheng"<< sz << endl; //cout << A <<"i"<<i<< endl; } A = sz; //A = AddWtoSmall(sz, A); //cout << sz << endl; } cout << A << endl; system("pause"); return 0; }
虽然都可以输出,但是速度慢,官方说运行超时~~
评测点序号 评测结果 得分 CPU使用 内存使用 下载评测数据 1 正确 10.00 0ms 1.335MB 输入 输出 2 正确 10.00 0ms 1.335MB 输入 输出 3 正确 10.00 0ms 1.335MB 输入 输出 4 正确 10.00 0ms 1.347MB 输入 输出 5 正确 10.00 62ms 1.347MB 输入 输出 6 运行超时 0.00 运行超时 1.386MB 输入 输出 7 运行超时 0.00 运行超时 1.386MB 输入 输出 8 运行超时 0.00 运行超时 1.386MB 输入 输出 9 运行超时 0.00 运行超时 1.386MB 输入 输出 10 运行超时 0.00 运行超时 1.386MB 输入 输出