You are on page 1of 2

PiSpigot.

java

import java.math.BigInteger; /** All BigInteger arithmetic is performed /** * Class PiSpigot * Outputs the first 233 digits of pi * computed though 1000 iterations * of an unbounded spigot algorithm * written by Jeremy Gibbons in 2005. */ public class PiSpigot { /** * Void main * The one function in PiSpigot, * in charge of computing and printing. * * @param args * @return none */ public static void main(String[] args) { BigInteger TWO = BigInteger.valueOf(2); BigInteger THREE = BigInteger.valueOf(3); BigInteger FOUR = BigInteger.valueOf(4); BigInteger SEVEN = BigInteger.valueOf(7); BigInteger BigInteger BigInteger BigInteger BigInteger BigInteger q r t k n l = = = = = = BigInteger.ONE; BigInteger.ZERO; BigInteger.ONE; BigInteger.ONE; BigInteger.valueOf(3); BigInteger.valueOf(3);

BigInteger nn; BigInteger nr; /** Used to print the decimal point immediately after the first digit is printed */ boolean firstDigit = true; for (int i = 0; i < 1000; i++) { /** if (4*q+r-t < n*t) */ Page 1

PiSpigot.java if (FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1) { System.out.print(n); /** Print decimal point immediately after the first digit is printed. */ if (firstDigit) { System.out.print("."); firstDigit = false; } // if /** nr = 10*(r-n*t) */ nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))); /** n = 10*(3*q+r)/t - (10*n) */ n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)); /** q *= 10 */ q = q.multiply(BigInteger.TEN); r = nr; System.out.flush(); } // if else { /** nr = (2*q+r)/l */ nr = TWO.multiply(q).add(r).multiply(l); /** nn = (q*(7*k+2)+r*l)/(t*l) */ nn = q.multiply(SEVEN.multiply(k).add(TWO)).add(r.multiply(l)).divide(t.multiply(l)); /** q *= k */ q = q.multiply(k); /** t *= l */ t = t.multiply(l); /** l += 2 */ l = l.add(TWO); /** k += 1 */ k = k.add(BigInteger.ONE); n = nn; r = nr; } // else } // for } // main } // class PiSpigot

Page 2

You might also like