How to resolve the algorithm Partition function P step by step in the Rust programming language
How to resolve the algorithm Partition function P step by step in the Rust programming language
Table of Contents
Problem Statement
The Partition Function P is the function P(n), where n∈ℤ, defined as the number of distinct ways in which n can be expressed as the sum of non-increasing positive integers.
P(n) can be expressed as the recurrence relation: The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ... This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video was viewed more than 100,000 times in the first couple of weeks after its release. In Wolfram Language, this function has been implemented as PartitionsP.
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive. Bonus task: show how long it takes to compute PartitionsP(6666).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Partition function P step by step in the Rust programming language
Source code in the rust programming language
// [dependencies]
// rug = "1.11"
use rug::Integer;
fn partitions(n: usize) -> Integer {
let mut p = Vec::with_capacity(n + 1);
p.push(Integer::from(1));
for i in 1..=n {
let mut num = Integer::from(0);
let mut k = 1;
loop {
let mut j = (k * (3 * k - 1)) / 2;
if j > i {
break;
}
if (k & 1) == 1 {
num += &p[i - j];
} else {
num -= &p[i - j];
}
j += k;
if j > i {
break;
}
if (k & 1) == 1 {
num += &p[i - j];
} else {
num -= &p[i - j];
}
k += 1;
}
p.push(num);
}
p[n].clone()
}
fn main() {
use std::time::Instant;
let n = 6666;
let now = Instant::now();
let result = partitions(n);
let time = now.elapsed();
println!("P({}) = {}", n, result);
println!("elapsed time: {} microseconds", time.as_micros());
}
You may also check:How to resolve the algorithm Sort disjoint sublist step by step in the Phix programming language
You may also check:How to resolve the algorithm Random number generator (device) step by step in the D programming language
You may also check:How to resolve the algorithm Numbers with equal rises and falls step by step in the BASIC programming language
You may also check:How to resolve the algorithm Deal cards for FreeCell step by step in the PHP programming language
You may also check:How to resolve the algorithm Ethiopian multiplication step by step in the Oz programming language