Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Created October 3, 2025 14:19
Show Gist options
  • Select an option

  • Save RandyMcMillan/06d9114246d3206a6653da0ef1351a96 to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/06d9114246d3206a6653da0ef1351a96 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
/// Calculates the value of the first identity's right-hand side: n - 1.
///
/// This function directly computes the right-hand side of the stated identity:
/// floor( (sum_{k=n}^inf 1/k^2)^-1 ) = n - 1.
///
/// # Arguments
/// * `n`: A positive integer (u64).
///
/// # Returns
/// The result (n - 1) as a u64.
///
/// # Panics
/// Panics if n is 0, as the identity is stated for a positive integer n.
pub fn identity_k_squared(n: u64) -> u64 {
if n == 0 {
panic!("n must be a positive integer.");
}
// Since n is a positive integer, n >= 1.
// The result is n - 1.
n - 1
}
/// Calculates the value of the second identity's right-hand side: 2 * n * (n - 1).
///
/// This function directly computes the right-hand side of the stated identity:
/// floor( (sum_{k=n}^inf 1/k^3)^-1 ) = 2 * n * (n - 1).
///
/// # Arguments
/// * `n`: A positive integer (u64).
///
/// # Returns
/// The result (2 * n * (n - 1)) as a u64.
///
/// # Panics
/// Panics if n is 0, as the identity is stated for a positive integer n.
pub fn identity_k_cubed(n: u64) -> u64 {
if n == 0 {
panic!("n must be a positive integer.");
}
// The result is 2 * n * (n - 1).
// The calculations are safe from overflow for reasonable u64 values of n.
// For large n, one should consider using u128 or BigInt.
2 * n * (n - 1)
}
// Example usage and verification (optional, for testing)
fn main() {
let n1 = 5;
let res1 = identity_k_squared(n1);
println!("For n = {}, floor((sum 1/k^2)^-1) = n - 1 = {}", n1, res1); // Output: 4
let n2 = 10;
let res2 = identity_k_cubed(n2);
// 2 * 10 * (10 - 1) = 20 * 9 = 180
println!("For n = {}, floor((sum 1/k^3)^-1) = 2n(n - 1) = {}", n2, res2); // Output: 180
}
@RandyMcMillan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment