官方答案:
@Test
public void method12() {
/**
* 吸血鬼數(shù)字的計算方法2
*/
Long starDate = System.currentTimeMillis();
int[] startDigit = new int[4];
int[] productDigit = new int[4];
int s1 = 0;
int s2 = 0;
for(int num1 = 10; num1 <= 99; num1++)
for(int num2 = num1; num2 <= 99; num2++) {
// Pete Hartley's theoretical result:
// If x·y is a vampire number then
// x·y == x+y (mod 9)
s1++;
if((num1 * num2) % 9 != (num1 + num2) % 9)
continue;
int product = num1 * num2;
startDigit[0] = num1 / 10;
startDigit[1] = num1 % 10;
startDigit[2] = num2 / 10;
startDigit[3] = num2 % 10;
productDigit[0] = product / 1000;
productDigit[1] = (product % 1000) / 100;
productDigit[2] = product % 1000 % 100 / 10;
productDigit[3] = product % 1000 % 100 % 10;
int count = 0;
for(int x = 0; x < 4; x++)
for(int y = 0; y < 4; y++) {
if(productDigit[x] == startDigit[y]) {
count++;
productDigit[x] = -1;
startDigit[y] = -2;
if(count == 4)
System.out.println(num1 + " * " + num2
+ " : " + product);
}
s2++;
}
}
System.out.println(s1);
System.out.println(s2);
System.out.println("總共花費時間:"+(System.currentTimeMillis() - starDate));
}
結(jié)果正確拆魏,最外層的雙重for循環(huán)執(zhí)行了4095次沥潭,里面的雙重for循環(huán)執(zhí)行了4960次驻仅,花費時間為1ms
第二種執(zhí)行算法:
@Test
public void method11() {
/**
* 吸血鬼數(shù)字第二種計算方法(只循環(huán)了232次)
*/
Long starDate = System.currentTimeMillis();
String[] ar_str1, ar_str2;
int sum = 0;
int from;
int to;
int i_val;
int count = 0;
// 雙重循環(huán)窮舉
for (int i = 10; i < 100; i++) {
// j=i+1避免重復
from = Math.max(1000 / i, i + 1);
to = Math.min(10000 / i, 100);
for (int j = from; j < to; j++) {
i_val = i * j;
// 下面的這個代碼与学,我個人并不知道為什么,汗顏
if (i_val % 100 == 0 || (i_val - i - j) % 9 != 0) {
continue;
}
count++;
ar_str1 = String.valueOf(i_val).split("");
ar_str2 = (String.valueOf(i) + String.valueOf(j)).split("");
Arrays.sort(ar_str1);
Arrays.sort(ar_str2);
if (Arrays.equals(ar_str1, ar_str2)) {// 排序后比較,為真則找到一組
sum++;
System.out.println("第" + sum + "組: " + i + "*" + j + "=" + i_val);
}
}
}
System.out.println("共找到" + sum + "組吸血鬼數(shù)");
System.out.println(count);
System.out.println("總共花費時間:"+(System.currentTimeMillis() - starDate));
}
只執(zhí)行了232次就將吸血鬼數(shù)拿到摊求,但耗費時間為10ms禽拔;
第二次算法博客地址:https://blog.csdn.net/java2000_net/article/details/3851203