1. 程式人生 > >N!的階乘附帶簡單大整數類的輸入輸出(暫時沒有深入的了解)

N!的階乘附帶簡單大整數類的輸入輸出(暫時沒有深入的了解)

ios sta 好的 n! width ear ati str cstring

Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!

我的思路:就想著大整數類去了,才發現自己還不能很好的掌握,其實這是一個大整數與int的乘法,一個50000的數組完全可以解決,看來分析問題的能力還是比較弱呀,希望能夠提升分析問題的全局能力!


#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n;
int a[50000];
while(cin>>n)
{
memset(a,0,sizeof(a));
a[0]=1;
int flag=0;
for(int i=2;i<=n;i++)
{
for(int j=0;j<=flag;j++)
a[j]*=i;
for(int j=0;j<=flag;j++)
{
if(a[j]>=10)
{
a[j+1]+=a[j]/10;
a[j]%=10;
}



}
if(a[flag+1])
{
while(a[++flag]>=10)
{
a[flag+1]+=a[flag]/10;
a[flag]%=10;
}
}


}
for(int i=flag;i>=0;i--)
cout<<a[i];
cout<<endl;




}



return 0;



}



大整數類的簡單輸入輸出,暫時就理解這些了,希望後續能夠加深搞出大整數的加減乘除!

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 #include<algorithm>
 6 using namespace std;
 7 struct Big
 8 {
 9     static const int BASE=100000000;
10     static const
int WIDTH=8; 11 vector<int > s; 12 Big operator =(const string &str) 13 { 14 s.clear(); 15 int x,len=(str.length()-1)/WIDTH+1; 16 for(int i=0;i<len;i++) 17 { 18 int end=str.length()-i*WIDTH; 19 int start=max(0,end-WIDTH); 20 sscanf(str.substr(start,end-start).c_str(),"%d",&x); 21 s.push_back(x); 22 23 } 24 return *this; 25 26 } 27 28 }; 29 istream &operator >>(istream &in,Big &b) 30 {string x; 31 in>>x; 32 b=x; 33 return in; 34 } 35 36 ostream &operator << (ostream &out, Big &x) 37 { 38 out<<x.s.back();//防止高位不足八位 39 for(int i=x.s.size()-2;i>=0;i--) 40 { 41 42 char buf[20]; 43 sprintf(buf,"%08d",x.s[i]); 44 for(int j=0;j<strlen(buf);j++) 45 out<<buf[j]; 46 } 47 return out; 48 49 } 50 int main() 51 { 52 Big a,b; 53 cin>>a>>b; 54 cout<<a<<" "<<b; 55 56 57 return 0; 58 59 60 }

N!的階乘附帶簡單大整數類的輸入輸出(暫時沒有深入的了解)