- 数与连分数
- 2017-07-19 12:07:08 @
#include<bits/stdc++.h>
using namespace std;
string s;
int a[10005];
int pos[10005];
int pow_ten(int n){
int num=1;
for(int i=0;i<n;i++){
num*=10;
}
return num;
}
int str2num(int start,int end){
int num=0,cnt,tem=1;
cnt=end-start-1;
for(int i=end-1,j=0;i>start;i--){
num+=(s[i]-'0')*pow_ten(j);
j++;
}
return num;
}
int gcd(int a,int b){
return !b?a:gcd(b,a%b);
}
int main(){
while(cin>>s){
memset(a,0,sizeof(a));
memset(pos,0,sizeof(pos));
if(s[0]=='['){
int j=0;
for(int i=0;i<s.size();i++){
if(s[i]<'0'||s[i]>'9'){
pos[j++]=i;
}
}
for(int i=0;i<j-1;i++){
//cout<<pos[i]<<" ";
a[i] = str2num(pos[i],pos[i+1]);
}
//cout<<endl;
//for(int i=0;i<j-1;i++){
// cout<<a[i]<<" ";
//}
//cout<<endl;
int num=1,den=a[j-2],tem;
for(int i=j-3;i>0;i--){
tem = num;
num = den;
den = den*a[i]+tem;
}
num = a[0]*den+num;
cout<<num<<'/'<<den<<endl;
}
else {
int pos;
for(int i=0;i<s.size();i++){
if(s[i]<'0'||s[i]>'9'){
pos=i;
}
}
//cout<<pos<<endl;
int num = str2num(-1,pos);
int den = str2num(pos,s.size());
//cout<<num<<" "<<den;
int temp1 = num;
num/=gcd(num,den);
den/=gcd(temp1,den);
int i=0,tem;
if(num==1){
cout<<'['<<0<<';'<<den<<']'<<endl;
}
else{
while(num!=1){
a[i++] = num/den;
tem = num%den;
num=den;
den =tem;
}
cout<<'[';
for(int j=0;j<i;j++){
if(j==0) cout<<a[j]<<';';
else if(j<i-1) cout<<a[j]<<',';
else cout<<a[j];
}
cout<<']'<<endl;
}
}
}
return 0;
}
1 条评论
-
hzg0226 LV 7 @ 2017-08-02 14:19:38
第四个点应该是格式问题,比如,3/1要输出3 [3;]时要输出[3]。醉了,也错了好多次。。
- 1