PTA:7-133 高精度運算 (20分)(一個測試點超時了,跪求大佬指教)

7-133 高精度運算 (20分)

在這裏插入圖片描述

我真的是太難了,專門用數組表示大數,最後不知道怎麼還是超時

貼上代碼:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int a[11000],b[11000],c[11000],s[11000],ia[11000],d[11000],ss[11000];
int main()
{
	int n,x;
	while(cin>>n>>x){
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(c,0,sizeof(c));
		memset(s,0,sizeof(s));
		memset(ss,0,sizeof(ss));
		int xx=x,at=0,st=0,bt=0,ct=0,it=0,dt=0;
	
		while(xx!=0){
			a[at++]=xx%10;
			b[bt++]=xx%10;
			s[st++]=xx%10;
			xx /= 10;
		}
//		cout<<"初始a:";
//		for(int j=at-1; j>=0; j--) cout<<a[j];
//		cout<<endl;
		
		for(int i=2; i<=n; i++){
			//計算pow(x,i)
//			cout<<endl<<"\npow:前";
//			for(int j=bt-1; j>=0; j--) cout<<b[j];		
//			cout<<endl<<"a:";
//			for(int j=at-1; j>=0; j--) cout<<a[j];
			memset(d,0,sizeof(d));
			for(int j=0; j<bt; j++){
				ct=0;
				memset(c,0,sizeof(c));
				for(int k=0; k<at; k++){   //每一行結果 
					int u=b[j]*a[k];
			//		cout<<"  u:"<<u;
					c[ct++] += u%10;
					c[ct] += u/10;
				}
//				cout<<endl<<"c: ";
//				for(int j=ct; j>=0; j--) cout<<c[j];
				
				int jj=j;
				for(int v=0; v<=ct; v++){  //將結果相加 
					int t=d[jj]+c[v];		
					d[jj]=t%10;
					d[jj+1]=d[jj+1]+t/10;
					jj++;	
				} 
				for(;d[jj]!=0;jj++);
				dt=jj;
//				cout<<endl<<"d:"; 
//				for(int j=dt-1; j>=0; j--) cout<<d[j];
			}
			for(;d[dt-1]==0;dt--);
			bt=dt;
			for(int j=0; j<dt; j++) b[j]=d[j];
//			cout<<endl<<"\npow:";
//			for(int j=bt-1; j>=0; j--) cout<<b[j];		
//			cout<<endl;
	
			
			//計算i*pow(x,i) 
			int ii=i,it=0,ct=0,dt=0;
			memset(d,0,sizeof(d));
			while(ii!=0){
				ia[it++]=ii%10;
				ii /= 10;
			}
			for(int j=0; j<bt; j++){
				ct=0;
				memset(c,0,sizeof(c));
				for(int k=0; k<it; k++){
					int u=b[j]*ia[k];
					c[ct++] += u%10;
					c[ct] += u/10;
				}
				int jj=j;
				for(int v=0; v<=ct; v++){  //將結果相加 
					int t=d[jj]+c[v];		
					d[jj]=t%10;
					d[jj+1]=d[jj+1]+t/10;
					jj++;	
				} 
				for(;d[jj]!=0;jj++);
				dt=jj;
			}
			for(;d[dt-1]==0;dt--);
//			cout<<"i*pow:";
//			for(int j=dt-1; j>=0; j--) cout<<d[j];
//			cout<<endl;
			
			//計算sum+i*pow(x,i) 
//			cout<<"sum前:";
//			for(int j=st-1; j>=0; j--) cout<<s[j];
//			cout<<endl; 
			
			int sst=0;
			memset(ss,0,sizeof(ss));
			int maxx=max(st,dt);
			for(int j=0; j<=maxx; j++){
				int u=d[j]+s[j];
				ss[sst] += u%10;
				ss[++sst] = u/10;
			}
			for(int j=0; j<=sst; j++) s[j]=ss[j];
			for(;ss[sst-1]==0;sst--);
			st=sst;
//			if(i==n){
//				cout<<"sum:";
//				for(int j=st-1; j>=0; j--) cout<<s[j];				
//			}
//			cout<<"sum:";
//			for(int j=st-1; j>=0; j--) cout<<s[j];
		}	
		for(int j=st-1; j>=0; j--) cout<<s[j];
		cout<<endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章