Rust Implementation of Problem 45

View source code here on GitHub!

Includes

Problem Solution

pub fn problems::p0045::p0045() -> utils::Answer
 1/*
 2Project Euler Problem 45
 3
 4Problem:
 5
 6Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
 7Triangle 	  	Tn=n(n+1)/2 	  	1, 3, 6, 10, 15, ...
 8Pentagonal 	  	Pn=n(3n−1)/2 	  	1, 5, 12, 22, 35, ...
 9Hexagonal 	  	Hn=n(2n−1) 	      	1, 6, 15, 28, 45, ...
10
11It can be verified that T285 = P165 = H143 = 40755.
12*/
13use crate::include::math::{hexagonal,pentagonal,triangle};
14use crate::include::utils::Answer;
15
16pub fn p0045() -> Answer {
17    let mut t_idx: u64 = 286;
18    let mut p_idx: u64 = 166;
19    let mut h_idx: u64 = 144;
20    let mut t_val = triangle(t_idx);
21    let mut p_val = pentagonal(p_idx);
22    let mut h_val = hexagonal(h_idx);
23    while !(t_val == p_val && p_val == h_val) {
24        while t_val < p_val || t_val < h_val {
25            t_idx += 1;
26            t_val = triangle(t_idx);
27        }
28        while p_val < t_val || p_val < h_val {
29            p_idx += 1;
30            p_val = pentagonal(p_idx);
31        }
32        while h_val < p_val || h_val < t_val {
33            h_idx += 1;
34            h_val = hexagonal(h_idx);
35        }
36    }
37    return Answer::Int(t_val.into());
38}

Tags: figurate-number, triangle-number