The price of Chess is 18446744073709551615 grains of rice

u128 pow commafy chess

Back when I was a kid my father told me the anecdote about the man who invented chess and then sold it to the Persian Shah. He did not ask for much. Just one grain of rice on the first square. Twice as many on the 2nd square and so on. According to the story the Shah laughed how little the man asked, but then could not pay it.

When I was a kid I always tried to figure out how many grains of rice that is. My father told me that it is 2^64-1, but that was meaningless to me. I remember I had tons of pieces of paper where I wrote down the calculations like this:

       1
       2
       4
       8
      16
      32
      64
     128
     ...

I don't remember ever reaching the end.

No with Rust it is easy, I just need to use the pow function:

examples/price-of-chess/src/main.rs

fn main() {
    let base: u128 = 2;
    let price = base.pow(64) - 1;
    println!("price: {}", price);
    println!("price: {}", commafy(price));

    let weight_in_gram = price as f64 * 0.025;
    println!("weight in gram: {}", weight_in_gram);
    println!("weight in kg: {}", (weight_in_gram / 1000.0).round());
    println!(
        "weight in metric ton: {}",
        (weight_in_gram / 1000.0 / 1000.0).round()
    );
    println!(
        "weight in metric ton: {}",
        commafy((weight_in_gram / 1000.0 / 1000.0).round() as u128)
    );
}

pub fn commafy<Integer: Into<u128> + Copy + std::fmt::Debug + std::fmt::Display>(
    num: Integer,
) -> String {
    let num = format!("{num}");
    let mut ix = 0;
    let num = num
        .chars()
        .rev()
        .map(|chr| {
            ix += 1;
            if ix % 3 == 1 && ix > 1 {
                format!(",{chr}")
            } else {
                format!("{chr}")
            }
        })
        .collect::<String>();
    num.chars().rev().collect::<String>()
}

price: 18446744073709551615
price: 18,446,744,073,709,551,615
weight in gram: 461168601842738800
weight in kg: 461168601842739
weight in metric ton: 461168601843
weight in metric ton: 461,168,601,843

That's a lot of rice. As I found on some places a grain of rice is about 0.02-0.04 gram

ps. Writing this post I found out that one ton is not always 1,000 kg. Oh.

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo