Helpful Information
 
 
Category: Pascal
Pascal -> Javascript - PI Program

Hi. I just found a nice Pascal Pi program that implements a Spigot algorithm. I converted it into Javascript, but found errors. Instead of printing the first 50 digits of pi, it printed 3.1415929695939598997999399929993999899949996999299. Can you help me find what is wrong? Thanks for your help.

Here is the original Pascal code:



program pi_spigot(input, output);
const n = 50;
len = 10*n div 3;
var i, j, k, q, x, nines, predigit: integer;
a : array[1..len] of integer;
count : integer;

procedure list(var count: integer; digit: integer);
begin
count := count +1;
write(digit:1);
if count mod 5 = 0 then
write(' ');
if count mod 20 = 0 then
writeln;
if count mod 100 = 0 then
writeln
end;

begin
count := -2;
for j := 1 to len do
a[j] := 2;
nines := 0;
predigit := 0;
for j := 1 to n do
begin
q := 0;
for i := len downto 1 do
begin
x := 10*a[i] +q*i;
a[i] := x mod (2*i-1);
q := x div (2*i-1)
end;
a[1] := q mod 10;
q := q div 10;
if q = 9 then
nines := nines +1
else
if q = 10 then
begin
list(count, predigit +1);
for k := 1 to nines do
list(count, 0);
predigit := 0; nines := 0
end
else
begin
list(count, predigit);
predigit := q;
if nines <> 0 then
begin
for k := 1 to nines do
list(count, 9);
nines := 0
end
end
end;
list(count, predigit)
end.



And here is my Javascript code:



<html>
<body>

<script>

var terms = 50;
var len = Math.floor((10 * terms) / 3);
var a = new Array(len);
var pi = new Array(terms);
var count = -2;
var nines = 0;
var predigit = 0;
var counter = 0;

for (j = 1; j <= len; j++)
{
a[j] = 2;
}

for (j = 1; j <= terms; j++)
{
q = 0;
for (i = len; i >= 1; i--)
{
x = 10 * a[i] + q * i;
a[i] = x % (2 * i - 1);
q = Math.floor(x / (2 * i - 1));
}
a[1] = q % 10;
q = Math.floor(q / 10);
if (q == 9) {
nines++;
} else {
if (q == 10) {
pi[counter] = predigit + 1;
counter++;
for (k = 1; k <= nines; k++)
{
pi[counter] = 0;
counter++;
}
predigit = 0;
nines = 0;
} else {
pi[counter] = predigit;
counter++;
predigit = q;
if (nines != 0) {
for(k = 1; k <= nines; k++)
{
pi[counter] = 9;
counter++;
}
}
}
}
}

pi[counter] = predigit;

document.write("3.");

for(k = 2; k <= terms; k++)
{
document.write(pi[k]);
}

</script>

</body>
</html>

nevermind, i found the error. gasp... i forgot to put a "nines = 0;". sorry for wasting space on your forum devshed :\