吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数的数字,其中最初的数字选取的数字可以任意排序。以两个0结尾的数字是不允许的,如下列数字都是吸血鬼数字:
1260=21*60
1827=21*87
2187=27*81
《Thinking in Java》第四版中第四章练习10里有这样相关的一道练习,找出4位数的所有吸血鬼数字
吸血鬼数字,其实有一个性质:
如果x*y是个吸血鬼数字,那么x*y=(x+y)mod 9
证明:
令d(x)函数为整数x所有位数和,那么对于所有数x有
d(x) mod 9=x mod 9
假设x*y是吸血鬼数字。那么根据定义,有d(x*y)=d(x)+d(y),因此有:
(x*y) mod 9=d(x*y) mod 9=(d(x)+d(y)) mod 9=(d(x)mod 9+d(y)mod 9)mod 9=(x mod 9 +y mod 9) mod 9
根据这个重要性质,《Thinking in Java》里给出了如下答案:
//: control/E10_Vampire.java
/****************** Exercise 10 *********************
* A vampire number has an even number of digits and
* is formed by multiplying a pair of numbers containing
* half the number of digits of the result. The digits
* are taken from the original number in any order.
* Pairs of trailing zeroes are not allowed. Examples
* include:
* 1260 = 21 * 60
* 1827 = 21 * 87
* 2187 = 27 * 81
* Write a program that finds all the 4-digit vampire
* numbers. (Suggested by Dan Forhan.)
****************************************************/
package control;
public class E10_Vampire {
public static void main(String[] args) {
int[] startDigit = new int[4];
int[] productDigit = new int[4];
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)
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);
}
}
}
}
} /* Output:
15 * 93 : 1395
21 * 60 : 1260
21 * 87 : 1827
27 * 81 : 2187
30 * 51 : 1530
35 * 41 : 1435
80 * 86 : 6880
*///:~
光看答案难以理解,这里给出一个解答