您的位置:首页 > 其它

吸血鬼数字

2017-07-14 09:28 106 查看
吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的,例如,下列数字都是“吸血鬼”数字:

1260 = 21 * 60

1827 = 21 * 87

2187 = 27 * 81

编写一个程序,找出4位数的所有吸血鬼数字。

private static void findVampire() {
int[] startDigit = new int[4];
int[] productDigit = new int[4];
int count = 0;

for (int i = 10; i < 100; i++) {
for (int j = i; j < 100; j++) {
int product = i * j;
if(product % 100 == 0 || (product - i - j) % 9 != 0)
continue;

count++;

startDigit[0] = i / 10;
startDigit[1] = i % 10;
startDigit[2] = j / 10;
startDigit[3] = j % 10;

productDigit[0] = product / 1000;
productDigit[1] = product % 1000 / 100;
productDigit[2] = product % 1000 % 100 / 10;
productDigit[3] = product % 1000 % 100  % 10;

int num = 0;
for (int x = 0; x < productDigit.length; x++) {
for (int y = 0; y < startDigit.length; y++) {
if(productDigit[x] == startDigit[y]){
num++;
productDigit[x] = -1;
startDigit[y] = -2;
if(num == 4)
System.out.println(i + " * " + j + " : " + product);
}
}
}
}
}
System.out.println("计算次数:" + count);
}


if(product % 100 == 0 || (product - i - j) % 9 != 0)
continue;


上述判断条件如何理解:

关于算法的解释,来自网友MT502

假设val = 1000a + 100b + 10c + d, 因为满足val = x * y, 则有x = 10a + b, y = 10c + d

则val - x - y = 990a + 99b + 9c = 9 * (110a + 11b + c), 所以val - x - y能被9整除。

所以满足该条件的数字必定能被9整除,所以可以直接过滤其他数字。

对于别的组合可能性,结果一样,比如

x=10c+a; y=10d+b;

val - x-y = (1000a + 100b + 10c + d) - (10c+a) - (10d +b) = 999a + 99b -9d

= 9 * (110a + 11b -d);

当然也能被9整除了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  吸血鬼数字