循環小數

第2題 循環小數

提交文件:float.pas/.cpp

輸入文件:float.in

輸出文件:float.out

 

給出一個循環小數XX = 0.a1a2...an(b1b2...bm)。 (b1b2...bm)代表小數的循環節。例如:0.5 = 0.50 = 0.5(0) = 0.5(00) = 1/2, 0.3(3) =0.333(33) = 1/3。現在,你需要將這個循環小數轉化爲分數形式A/B(A和B的公約數必須爲1)

 

輸入格式:

第一行有兩個正整數n, m

第二行有n個正整數a1a2...an

第三行有m個正整數b1b2...bm

輸出格式:

輸出兩個正整數AB,用空格隔開,表示分數A/B

 

輸入樣例:

4 2

3333

33

 

輸出樣例:

1 3

數據範圍:

對於20%數據 1 ≤n, m ≤ 6

對於所有數據 1 ≤ n, m≤ 8

分析:

將純循環小數改寫成分數,分子是一個循環節的數字組成的數;分母各位數字都是9,9的個數與循環節中的數字的個數相同.例如0.111...=1/9、0.12341234...=1234/9999

混循環小數改寫成分數,分子是不循環部分與第一個循環節連成的數字組成的數,減去不循環部分數字組成的數之差;分母的頭幾位數字是9,末幾位數字是0,9的個數跟循環節的數位相同,0的個數跟不循環部分的數位相同.

代碼

var
  n,m,a,b:int64;


function gcd(a,b:int64):int64;
begin
  if b=0 then
    exit(a);
  exit(gcd(b,a mod b));
end;


procedure init;
begin
  readln(n,m);
  readln(a);
  readln(b);
end;


procedure main;
var
  i:longint;
  num,ans,tot:int64;
begin
  num:=a;
  ans:=0;
  for i:=1 to m do
    begin
      num:=num*10;
      ans:=ans*10+9;
    end;
  num:=num+b-a;
  for i:=1 to n do
    ans:=ans*10;
  tot:=gcd(num,ans);
  write(num div tot,' ',ans div tot);
end;


begin
  assign(input,'float.in');reset(input);
  assign(output,'float.out');rewrite(output);
  init;
  main;
  close(input);close(output);
end.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章