Projecteuler.net – Problem 44 – Java

http://projecteuler.net/problem=44

I populated a Set with a range of Pentagonal numbers that I thought might contain the result. Then I check if the Sums and Differences are already in the Set. This method is not optimum as it will end up checking pairs twice due to how I iterated through the Set.

Josh

import java.util.HashSet;
import java.util.Set;

public class Euler44 {

	public static void main(String[] args) {
		
		boolean eD;		// .contains result for Set
		boolean eS;		// .contains result for Set
		
		// build and Set of Pentagonal numbers
		Set<Long> p = new HashSet<Long>();
		
		for (int i = 1; i < 5000; i++) {
			Long x = new Long((i * ((3 * i) - 1) / 2));
			p.add(x);
		}
		
		for (Long element1 : p) {
			for (Long element2 : p) {
				
				Long elementSum = new Long(element1 + element2);
				Long elementDifference = new Long(Math.abs(element2 - element1));
				
				eD = p.contains(elementDifference);
				eS = p.contains(elementSum);
				
				if (eD && eS) {
					System.out.println(elementDifference);
					
				}								
			}			
		}	
		
	}

}

This entry was posted in Java, Project Euler. Bookmark the permalink.

Leave a Reply