问题描述:
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(3n1)/2 | 1, 5, 12, 22, 35, ... | ||
Hexagonal | Hn=n(2n1) | 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.
解决问题:
package projecteuler; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Problem45 { public static void main(String[] args){ Map<Long, Long> number = new HashMap<Long, Long>(); Long Triangle ; Long Pentagonal ; Long Hexagonal ; Long T = 286L; boolean find = false; do{ Triangle = (T*(T+1))/2L; Pentagonal = (T*(3*T-1))/2L; Hexagonal = T*(2*T-1L); number.put(Hexagonal, 2L); if(number.containsKey(Triangle)){ Long value = number.get(Triangle); if(value==1){ find = true; System.out.println("Triangle:"+Triangle); }else{ number.remove(Triangle); number.put(Triangle, 1L); } } if(number.containsKey(Pentagonal)){ Long value = number.get(Pentagonal); if(value==1){ find = true; System.out.println("Pentagonal:"+Pentagonal); }else{ number.remove(Pentagonal); number.put(Pentagonal, 1L); } } System.out.println("T:"+T); T++; }while(!find); long r = T*(T+1)/2L; System.out.print(r); } }