2
0

pi.pp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. program pi;
  2. {$ifdef fpc}
  3. {$mode objfpc}
  4. {$endif fpc}
  5. {$APPTYPE CONSOLE}
  6. {$h+}
  7. uses
  8. timer;
  9. function ComputePi(NumDigits: Integer): string;
  10. var
  11. A: array of LongInt;
  12. I, J, K, P, Q, X, Nines, Predigit: Integer;
  13. PiLength: Integer;
  14. begin
  15. start;
  16. SetLength(A, 10*NumDigits div 3);
  17. SetLength(Result, NumDigits+1);
  18. PiLength := 1;
  19. for I := Low(A) to High(A) do
  20. A[I] := 2;
  21. Nines := 0;
  22. Predigit := 0;
  23. for J := 0 to NumDigits-1 do
  24. begin
  25. Q := 0;
  26. P := 2 * High(A) + 1;
  27. for I := High(A) downto Low(A) do
  28. begin
  29. X := 10*A[I] + Q*(I+1);
  30. A[I] := X mod P;
  31. Q := X div P;
  32. P := P - 2;
  33. end;
  34. A[Low(A)] := Q mod 10;
  35. Q := Q div 10;
  36. if Q = 9 then
  37. Inc(Nines)
  38. else if Q = 10 then
  39. begin
  40. Result[PiLength] := Chr(Predigit + 1 + Ord('0'));
  41. for K := 1 to Nines do
  42. Result[PiLength+K] := '0';
  43. PiLength := PiLength + Nines + 1;
  44. Predigit := 0;
  45. Nines := 0;
  46. end
  47. else
  48. begin
  49. Result[PiLength] := Chr(Predigit + Ord('0'));
  50. Predigit := Q;
  51. for K := 1 to Nines do
  52. Result[PiLength+K] := '9';
  53. PiLength := PiLength + Nines + 1;
  54. Nines := 0;
  55. end;
  56. end;
  57. Result[PiLength] := Chr(Predigit + Ord('0'));
  58. stop;
  59. end;
  60. var
  61. NumDigits: Integer;
  62. Code: Integer;
  63. F: TextFile;
  64. result : string;
  65. begin
  66. if ParamCount = 0 then
  67. WriteLn('usage: pi #DIGITS [FILE]')
  68. else
  69. begin
  70. Val(ParamStr(1), NumDigits, Code);
  71. if Code <> 0 then
  72. begin
  73. WriteLn('Invalid # digits: ', ParamStr(1));
  74. Halt(1);
  75. end;
  76. if ParamCount > 1 then
  77. begin
  78. AssignFile(F, ParamStr(2));
  79. Rewrite(F);
  80. WriteLn(F, ComputePi(NumDigits));
  81. CloseFile(F);
  82. end
  83. else
  84. begin
  85. result:=ComputePi(NumDigits);
  86. WriteLn(result);
  87. end;
  88. end;
  89. end.