Rust Implementation of Problem 44

View source code here on GitHub!

Includes

Problem Solution

pub fn problems::p0044::p0044() -> utils::Answer
 1/*
 2Project Euler Problem 44
 3
 4Problem:
 5
 6Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:
 7
 81, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
 9
10It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
11
12Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = ``|Pk − Pj|``
13is minimised; what is the value of D?
14*/
15use std::cmp::min;
16
17use crate::include::math::pentagonal;
18use crate::include::utils::Answer;
19
20
21fn is_pentagonal(x: i64) -> bool {
22    let root = ((24 * x + 1) as f64).sqrt();
23    if root != root.round() {
24        return false;
25    }
26    return (1.0 + root) % 6.0 == 0.0;
27}
28
29pub fn p0044() -> Answer {
30    let mut d: i64 = 1_000_000_000_000;
31    let pentagonals = (1..2_500).map(pentagonal).collect::<Vec<i64>>();
32    for (idx, &k) in pentagonals.iter().enumerate() {
33        for &j in &pentagonals[..idx] {
34            if is_pentagonal(j + k) && is_pentagonal(k - j) {
35                d = min(d, (k - j).abs());
36            }
37        }
38    }
39    return Answer::Int(d.into());
40}

Tags: figurate-number