123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- extern crate num;
- extern crate test;
- use std::str::FromStr;
- use std::num::FromPrimitive;
- use test::Bencher;
- use num::{BigInt, Integer, One, Zero};
- struct Context {
- numer: BigInt,
- accum: BigInt,
- denom: BigInt,
- }
- impl Context {
- fn new() -> Context {
- Context {
- numer: One::one(),
- accum: Zero::zero(),
- denom: One::one(),
- }
- }
- fn from_int(i: int) -> BigInt {
- FromPrimitive::from_int(i).unwrap()
- }
- fn extract_digit(&self) -> int {
- if self.numer > self.accum {return -1;}
- let (q, r) =
- (self.numer * Context::from_int(3) + self.accum)
- .div_rem(&self.denom);
- if r + self.numer >= self.denom {return -1;}
- q.to_int().unwrap()
- }
- fn next_term(&mut self, k: int) {
- let y2 = Context::from_int(k * 2 + 1);
- self.accum = (self.accum + (self.numer << 1)) * y2;
- self.numer = self.numer * Context::from_int(k);
- self.denom = self.denom * y2;
- }
- fn eliminate_digit(&mut self, d: int) {
- let d = Context::from_int(d);
- let ten = Context::from_int(10);
- self.accum = (self.accum - self.denom * d) * ten;
- self.numer = self.numer * ten;
- }
- }
- fn pidigits(n: int) {
- let mut k = 0;
- let mut context = Context::new();
- for i in range(1, n + 1) {
- let mut d;
- loop {
- k += 1;
- context.next_term(k);
- d = context.extract_digit();
- if d != -1 {break;}
- }
- print!("{}", d);
- if i % 10 == 0 {print!("\t:{}\n", i);}
- context.eliminate_digit(d);
- }
- let m = n % 10;
- if m != 0 {
- for _ in range(m, 10) { print!(" "); }
- print!("\t:{}\n", n);
- }
- }
- static DEFAULT_DIGITS: int = 512;
- #[bench]
- fn use_bencher(b: &mut Bencher) {
- b.iter(|| pidigits(DEFAULT_DIGITS))
- }
- fn main() {
- let args = std::os::args();
- let args = args.as_slice();
- let n = if args.len() < 2 {
- DEFAULT_DIGITS
- } else {
- FromStr::from_str(args[1].as_slice()).unwrap()
- };
- pidigits(n);
- }
|