Project Euler(32)
Posted on Wednesday, December 31st, 2008 at 9:15 pm by Universe QueenProblem 32:
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigitial.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
Answer: 45228
Implementation in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | import java.util.*; public class Euler32 { public static boolean isRepeat( int n ) { String s = String.valueOf( n ); for( int i=s.length()-1; i>=0; i-- ) { for( int j=0; j<i; j++ ) { if( s.charAt(i) == s.charAt(j) || s.charAt(i) == '0' || s.charAt(j) == '0' ) { return true; } } } return false; } public static void main(String[] args) { int result = 0; Set set = new TreeSet(); String tmp; int r; for( int a=1; a<=98765; a++ ) { if( isRepeat(a) ) { continue; } for( int b=1; b<=98765; b++ ) { if( isRepeat(b) ) { continue; } tmp = String.valueOf(a) + String.valueOf(b); if( tmp.length() > 5 ) { break; } if( isRepeat( Integer.valueOf(tmp) ) ) { continue; } r = a * b; if( isRepeat( r ) ) { continue; } tmp = tmp + String.valueOf(r); if( tmp.length() != 9 ) { continue; } if( !isRepeat( Integer.valueOf(tmp) ) ) { set.add( r ); } } } Iterator it = set.iterator(); while( it.hasNext() ) { result += (Integer)(it.next()); } System.out.println( result ); } } |
