From charlesreid1

No edit summary
No edit summary
Line 1: Line 1:
Problem 52 on Project Euler: https://projecteuler.net/problem=52
Problem 52 on Project Euler: https://projecteuler.net/problem=52


Link to solution on git.charlesreid1.com: https://charlesreid1.com:3000/cs/euler
Link to solution on git.charlesreid1.com: https://charlesreid1.com:3000/cs/euler/src/master/052/PermutedMultiples.java
 
The key here was structuring the program so that it uses chained method calls,
so that you stop multiplying and move on to the next candidate as soon as you have a failure.
That, combined with the concept that we wanted
the same SET of digits, meant we needed
a method that would turn an arbitrary integer
into a set of digits,
and we could compare as we go.
 
Here's how the final product looks:
 
<pre>
public class PermutedMultiples {
public static void main(String[] args) {
boolean found = false;
Set<Integer> digits = new HashSet<Integer>();
 
int n = 100;
while(!found) {
// 1x
Set<Integer> s = getSet(n);
if(s.equals(getSet(2*n))) {
if(s.equals(getSet(3*n))) {
if(s.equals(getSet(4*n))) {
if(s.equals(getSet(5*n))) {
if(s.equals(getSet(6*n))) {
System.out.println("x = "+n);
found = true;
}
}
}
}
}
n++;
}
}
 
public static Set<Integer> getSet(int n) {
Set<Integer> result = new HashSet<Integer>();
while(n!=0) {
int r = n%10;
n = n/10;
result.add(r);
}
return result;
}
 
}
</pre>
 




{{ProjectEulerFlag}}
{{ProjectEulerFlag}}

Revision as of 03:09, 5 July 2017

Problem 52 on Project Euler: https://projecteuler.net/problem=52

Link to solution on git.charlesreid1.com: https://charlesreid1.com:3000/cs/euler/src/master/052/PermutedMultiples.java

The key here was structuring the program so that it uses chained method calls, so that you stop multiplying and move on to the next candidate as soon as you have a failure. That, combined with the concept that we wanted the same SET of digits, meant we needed a method that would turn an arbitrary integer into a set of digits, and we could compare as we go.

Here's how the final product looks:

public class PermutedMultiples { 
	public static void main(String[] args) { 
		boolean found = false;
		Set<Integer> digits = new HashSet<Integer>();

		int n = 100;
		while(!found) { 
			// 1x 
			Set<Integer> s = getSet(n);
			if(s.equals(getSet(2*n))) {
				if(s.equals(getSet(3*n))) {
					if(s.equals(getSet(4*n))) {
						if(s.equals(getSet(5*n))) {
							if(s.equals(getSet(6*n))) {
								System.out.println("x = "+n);
								found = true;
							}
						}
					}
				}
			}
			
			n++;
		}
	}

	public static Set<Integer> getSet(int n) { 
		Set<Integer> result = new HashSet<Integer>();
		while(n!=0) { 
			int r = n%10;
			n = n/10;
			result.add(r);
		}
		return result;
	}

}