- 数与连分数
- 2016-05-24 21:08:54 @
var s,r,t:string;
i,i1,l1,mo,j,k,l,n,m,tot,code,d,len,x,ans:longint;
p,p1:extended;
a:array [1..1000] of string;
f:boolean;
procedure qq(w:string);
var r,t:string;
p,q,i,j,k,p1,q1,c:longint;
begin
r:='';
i:=-1;
for i:=1 to length(w) do
if s[i]='/' then begin
val(copy(w,1,pos('/',w)-1),p);
val(copy(w,pos('/',w)+1,length(w)-pos('/',w)),q); end;
if i=-1 then begin writeln(w);exit; end;
k:=p mod q;p1:=p;q1:=q;
while k>0 do begin p1:=q1;q1:=k;k:=p1 mod q1; end;p:=p div q1;q:=q div q1;
if p mod q=0 then begin write(p div q);exit; end;
str(p div q,t);
r:='['+t+';';
c:=q;q:=p mod q;p:=c;
while q<>1 do
begin
str(p div q,t);r:=r+t+',';
c:=q;q:=p mod q;p:=c;
if q=0 then begin write(p div q);break; end;
end;
if p<>1 then begin str(p,t);r:=r+t+','; end;
r[length(r)]:=']';
inc(ans);a[ans]:=r;
end;
begin
while not eof do
begin
readln(s);
if s[1]='[' then
begin
p:=0;p1:=0;fillchar(a,sizeof(a),0);
for i:=length(s)-1 downto 1 do begin
if (s[i]=',') or (s[i]=';') or (s[i]='[') then begin
val(copy(s,i+1,len),x,code);
if d=0 then begin n:=1;d:=x
end else begin
n:=x*d+n;
code:=n;n:=d;d:=code;
end;
len:=0
end else inc(len);
end;
code:=n;n:=d;d:=code;
i1:=n;l1:=d;mo:=i1 mod l1;
while mo<>0 do begin i1:=l1;l1:=mo;mo:=i1 mod l1; end;
n:=n div l1;d:=d div l1;
if d=1 then begin inc(ans);str(n,a[ans]);end else begin inc(ans);str(n,a[ans]);a[ans]:=a[ans]+'/';str(d,r);a[ans]:=a[ans]+r; end;
end
else
qq(s);
end;
for i:=1 to ans do writeln(a[i]);
end.
1 条评论
-
142857 LV 8 @ 2017-01-19 13:23:14
#include<stdio.h>
char a[1048576];
FILE* f;
void zh(int fz,int fm,bool a)
{
if(a)
{
printf("[");
}
printf("%d",fz/fm);
if(fz%fm==0)
{
printf("]\n");
}
else
{
if(a)
{
printf(";");
}
else
{
printf(",");
}
zh(fm,fz%fm,0);
}
}
void zh2(int &fz,int &fm)
{
char c;
int d;
fscanf(f,"%d%c",&d,&c);
if(c==']')
{
fz=d;
fm=1;
return;
}
zh2(fm,fz);
fz+=fm*d;
}
int main()
{
int fz=0,fm=0;
while(scanf("%s",a)>0)
{
if(a[0]=='[')
{
f=fopen("1","w");
fprintf(f,"%s",a);
fclose(f);
f=fopen("1","r");
char c;
fscanf(f,"%c",&c);
zh2(fz,fm);
printf("%d/%d\n",fz,fm);
}
else
{
sscanf(a,"%d%*c%d",&fz,&fm);
zh(fz,fm,1);
}
}
return 0;
}
c程序
- 1