1 unstable release

Uses new Rust 2024

0.1.0 Jun 4, 2026

#2391 in Algorithms

Apache-2.0

4KB

Pi Digit Generator (Rust)

A simple Rust implementation of a π (Pi) digit generator using a spigot-style algorithm. This program computes and returns the first n digits of Pi as a string.

Features

  • Pure Rust implementation
  • No external dependencies
  • Generates Pi digits sequentially
  • Returns the result as a formatted string (3.14159...)

Code

pub fn compute_pi_digits(n: usize) -> String {
    // Each element holds intermediate values
    let len = n * 10 / 3 + 1;
    let mut arr = vec![2; len];

    let mut result = String::with_capacity(n + 2);
    let mut carry;

    for i in 0..n {
        let mut sum = 0;

        for j in (0..len).rev() {
            let x = arr[j] * 10 + sum * (j + 1);
            arr[j] = x % (2 * j + 1);
            sum = x / (2 * j + 1);
        }

        arr[0] = sum % 10;
        carry = sum / 10;

        result.push_str(&carry.to_string());

        if i == 0 {
            result.push('.');
        }
    }

    result
}

Usage

fn main() {
    let pi = compute_pi_digits(20);
    println!("{}", pi);
}

Example output:

3.1415926535897932384

How It Works

This implementation uses a spigot-style algorithm that generates digits of Pi one at a time using integer arithmetic.

The algorithm:

  1. Initializes a working array of intermediate values.
  2. Iteratively performs division and remainder operations.
  3. Extracts one decimal digit per iteration.
  4. Appends the digit to the output string.
  5. Inserts the decimal point after the first digit (3).

Because only integer arithmetic is used, the implementation avoids floating-point precision limitations.

Complexity

  • Time Complexity: O(n²)
  • Space Complexity: O(n)

Where n is the number of digits requested.

Limitations

  • Intended for educational and demonstration purposes.
  • Performance decreases for very large values of n.
  • More advanced algorithms such as Chudnovsky or BBP are significantly faster for computing millions of digits.

License

MIT License

No runtime deps