woensdag 16 maart 2011

Euler problem 45

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
TriangleTn=n(n+1)/21, 3, 6, 10, 15, ...
PentagonalPn=n(3n−1)/21, 5, 12, 22, 35, ...
HexagonalHn=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.


analyse:
1) Every Hexagonal is also a Triangle.
performance improvements: 
2) Start looping with Hexagonal numbers because they increase faster than other two number types.
3) H143 gives 40755 so start with n = 144.
4) use difference: H(n) - H(n-1) = n(2n-1) - ((n-1)(2(n-1)-1)) = 4 * n - 3



An alternate solution is to make use of the square root formula. x = (-b+- sqrt(b2-4ac))/2a

When we rewrite the pentagon formule P(n) = n(3n-1)/2 
we get 1.5n*n - 0.5n - P(n) = 0 where P(n) = H(n)



Problem45 =  1533776805 elapsed time:    1 ms. Test Passed.

Geen opmerkingen:

Een reactie posten