Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ... It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
My Implementation:
I used a HashSet for fast searching. I got the right answer after experimenting with the size of the HashSet. 100000 worked for me.
void Main()
{
var pen = Pentagonals(100000);
var hex = Hexagonals(100000);
foreach(var n in Triangles()){
if(pen.Contains(n) && hex.Contains(n) && n > 40755){
Console.WriteLine(n);
return;
}
}
}
IEnumerable<BigInteger> Triangles()
{
for(BigInteger n = 1;;n++)
{
yield return (n * (n + 1) / 2);
}
}
HashSet<BigInteger> Pentagonals(int limit)
{
HashSet<BigInteger> set = new HashSet<BigInteger>();
for(BigInteger n = 1;n <= limit;n++)
{
set.Add(n * (3 *n - 1) / 2);
}
return set;
}
HashSet<BigInteger> Hexagonals(int limit)
{
HashSet<BigInteger> set = new HashSet<BigInteger>();
for(BigInteger n = 1;n <= limit;n++)
{
set.Add(n * (2*n - 1));
}
return set;
}
How can I improve this?