Project Euler – Problem 45

Problem 45:
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.

import java.math.BigInteger;

class runner
{
	private static BigInteger getTriangle(int n){
		BigInteger x = new BigInteger(""+n);
		x = x.multiply(new BigInteger(""+(n+1)));
		x = x.divide(new BigInteger("2"));
		return x;//n*(n+1)/2;
	}
	private static BigInteger getPentagonal(int n){
		BigInteger x = new BigInteger(""+n);
		x = x.multiply(new BigInteger("3"));
		x = x.subtract(new BigInteger("1"));
		x = x.multiply(new BigInteger(""+n));
		x = x.divide(new BigInteger("2"));
		
		return x;//n*(3*n-1)/2;
	}
	private static BigInteger getHexagonal(int n){
		BigInteger x = new BigInteger(""+n);
		x = x.multiply(new BigInteger("2"));
		x = x.subtract(new BigInteger("1"));
		x = x.multiply(new BigInteger(""+n));
		
		return x;//n*(2*n-1);
	}
	
	public static void main (String[] args) throws java.lang.Exception
	{
		long time = System.currentTimeMillis();
		
		int ti = 285+1;
		int pi = 165;
		int hi = 143;
		
		BigInteger pval = getPentagonal(pi);
		BigInteger hval = getHexagonal(hi);
		BigInteger tval = new BigInteger("0");
		while(true){
			tval = getTriangle(ti);
			
			while(tval.compareTo(pval) > 0){
				pi++;
				pval = getPentagonal(pi);
			}
			
			while(tval.compareTo(hval) > 0){
				hi++;
				hval = getHexagonal(hi);
			}
			
			if(pval.compareTo(tval) == 0 && hval.compareTo(tval) == 0){
				break;
			}
			ti++;
		}
		
		
		System.out.println("tval: "+tval);

		System.out.println("time: "+(System.currentTimeMillis() - time));
	}
}


Note: You can remove the entirety of Triangle Numbers due to the fact that the set of Hexagonal numbers contains Triangle numbers. Rewriting the above code without triangles brings down the execution time from 171ms to 111ms.