- [P1009 阶乘之和](https://www.luogu.com.cn/problem/P1009)
QAQ,刚开始看完题直接立刻按照题目阶乘相加写出了程序,数据使用int类型处理,4个测试点只通过两个。
感觉应该是int型数据不够大,存不下结果,然后换成了long long测试一遍还是不行,又换成了unsigned long long,还是不够大,
下载了第三个测试点看了一下,发现是22的阶乘,结果是1177652997443428940313, ̄□ ̄||。。。。。。。。。。
//这个不行 #include<iostream> #include<cmath> #include<iomanip> #include <stdio.h> #include <math.h> using namespace std; unsigned long long jc(unsigned long long n); int main() { unsigned long long n,s=1,s2=0; cin>>n; for(unsigned long long i = 1; i<=n; i++) s2+=jc(i); cout<<s2; return 0; } unsigned long long jc(unsigned long long n) { unsigned long long s = 1; for(unsigned long long i = 1; i<=n; i++) s*=i; return s; }
发现题目提示用高精度计算,花了大半天用数组写了一个超长数据加法乘法器终于全部ac,
#include<iostream> #include<sstream> using namespace std; class Operator { public: string input; int data[100]; int length; void init(); Operator(string s); void setdata(string s); void printdata(); int adder(Operator ope); int subtractor(Operator ope); int multiplier(Operator ope,int n); int divider(Operator ope); }; Operator::Operator(string s) { if(s=="0") { init(); } else { for(int i = 0; i<100; i++) { data[i]=0; } input = s; length = s.length(); stringstream ss; for(int i = 0; i<length; i++) { ss<<s[i]; ss>>data[length-i-1]; ss.clear(); } } } void Operator::init() { for(int i = 0; i<100; i++) { data[i]=0; } input = ""; this->length = 0; } void Operator::printdata() { cout<<"data = "; for(int i = length-1; i>=0; i--) { cout<<data[i]; } if(length==0) cout<<"0"; cout<<" string ="<<input; cout<<" length = "<<length; cout<<endl; } void Operator::setdata(string s) { input = s; length = s.length(); stringstream ss; for(int i = 0; i<length; i++) { ss<<input[i]; ss>>data[length-i-1]; ss.clear(); } } int Operator::adder(Operator ope) { int add_bit = 0; this->length = max(this->length,ope.length); for(int i = 0; i<max(this->length,ope.length); i++) { int d = this->data[i]+ope.data[i]; if(add_bit!=0) d+=1; if(d>9) add_bit = 1; else add_bit = 0; this->data[i] = d%10; } if(add_bit==1) { this->data[length]=1; this->length = length+1; } stringstream ss; input.resize(this->length); for(int i = 0; i<this->length; i++) { ss<<data[this->length-i-1]; ss>>this->input[i]; ss.clear(); } return 1; } int Operator::multiplier(Operator ope,int n) { Operator ope_copy(ope.input); for(int i = 1; i<n; i++) { this->adder(ope_copy); } return 1; } int Operator::subtractor(Operator ope) { return 0; } int Operator::divider(Operator ope) { return 0; } int main() { int n; cin>>n; Operator sum_factorial("0"); for(int i = 1; i<=n; i++) { Operator factorial("1"); for(int j = 1; j<=i; j++) { factorial.multiplier(factorial,j); } sum_factorial.adder(factorial); } cout<<sum_factorial.input; return 0; }
真不容易,想刷点大水题。。。。。。。。。。