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 pandigital.
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.
公式 a * b = c;
一共9个数, 所以推算c只能是4位数, a是1到4位, b是1到2位。
至于a, b , c是否是pandigital products, 没费脑子一位一位的算,直接转成List,接着排序。
于是暴力的方法就这么产生了:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PandigitalProducts {
public static void main(String[] args) {
long before = System.currentTimeMillis();
new PandigitalProducts().calculate();
System.out.println("elapsed time is : " + (System.currentTimeMillis() - before));
}
private void calculate() {
List<Integer> products = new ArrayList<Integer>();
int product = 0;
int sum = 0;
for (int i = 1; i < 9999; i++) {
for (int j = 1; j < 99; j++) {
product = i * j;
if (isPandigital(i, j, product) && !products.contains(product)) {
products.add(product);
sum += product;
System.out.println("i = " + i + " , j = " + j + " , product = " + product);
}
}
}
System.out.println("sum of all products is : " + sum);
}
private boolean isPandigital(int a, int b, int product) {
List<String> numberList = new ArrayList<String>();
String idealStr = "123456789";
String whatWeGotStr = "";
String temp = "" + a + b + product;
String[] strArr = temp.split("");
for (String s : strArr) {
numberList.add(s);
}
Collections.sort(numberList);
for (String s : numberList) {
whatWeGotStr += s;
}
if (whatWeGotStr.equals(idealStr)) {
return true;
}
return false;
}
}
console :
i = 138 , j = 42 , product = 5796
i = 157 , j = 28 , product = 4396
i = 159 , j = 48 , product = 7632
i = 186 , j = 39 , product = 7254
i = 198 , j = 27 , product = 5346
i = 1738 , j = 4 , product = 6952
i = 1963 , j = 4 , product = 7852
sum of all products is : 45228
elapsed time is : 2099