算法:吸血鬼数字算法

吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘得到,而这对数字各包含乘积一半位数的数字,其中从最初数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的。下面是一些吸血鬼数字:

15*93: 1395
21*60: 1260
21*87: 1827

写一个程序找出4位数中的所有吸血鬼数字:

下列解法为Java编程思想提供的参考解法

 1         int[] startDigit = new int[4]; //start digit
 2         int[] productDigit = new int[4];   //product digit
 3         for (int num1 = 10; num1 <= 99; num1++){
 4             for (int num2 = num1; num2 <=99; num2++){
 5                 if ((num1 * num2) % 9 != (num1 + num2) % 9)
 6                     continue;
 7                 int product = num1 * num2;
 8                 startDigit[0] = num1 / 10;
 9                 startDigit[1] = num1 % 10;
10                 startDigit[2] = num2 / 10;
11                 startDigit[3] = num2 % 10;
12                 productDigit[0] = product / 1000;
13                 productDigit[1] = (product % 1000) / 100;
14                 productDigit[2] = product % 1000 % 100 /10;
15                 productDigit[3] = product % 1000 % 100 % 10;
16                 int count = 0;
17                 for (int x = 0; x < 4; x++){
18                     for (int y = 0; y < 4; y++){
19                         if (productDigit[x] == startDigit[y]){
20                             count++;
21                             productDigit[x] = -1;
22                             startDigit[y] = -2;
23                             if (count == 4)
24                                 System.out.println(num1 + " * " + num2 + ":" + product);
25                         }
26                     }
27                 }
28             }
29         }
Vampire Algorithm

提示:

4位吸血鬼数字形式为abcd

1000a  + 100b + 10c + d = (10a + b) + (10c + d)

1000a  + 100b + 10c + d = (10a + c) + (10b + d)

......

无论何种形式, 我们发现多项式中除了三个一位数以外都是10的倍数,所以很容易想到等式两边同时%9,等式仍然成立。

如果%9等式不成立,那么这个数一定不是吸血鬼数字。

原文地址:https://www.cnblogs.com/dgzhangning/p/7498689.html