吸血鬼数字
2017-07-14 09:28
106 查看
吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的,例如,下列数字都是“吸血鬼”数字:
1260 = 21 * 60
1827 = 21 * 87
2187 = 27 * 81
编写一个程序,找出4位数的所有吸血鬼数字。
上述判断条件如何理解:
关于算法的解释,来自网友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整除了
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整除了
相关文章推荐
- 吸血鬼数字、斐波那契数列算法
- 吸血鬼数字
- 吸血鬼数字
- Think in java中关于吸血鬼数字问题的算法
- 找出四位数的所有吸血鬼数字(JAVA)
- 《java编程思想》第四章练习10找出所有四位数的吸血鬼数
- Java 吸血鬼数字
- Java - 吸血鬼数字
- 查找四位数的吸血鬼数字(java编程思想)
- java输出吸血鬼数字小结
- 4位数吸血鬼数字算法
- Java 提高(1)----- java中的goto语句
- 【java】吸血鬼数字
- Java编程思想:吸血鬼数字
- sql注入总结
- 《TP5.0学习笔记---请求和响应篇》
- 循环控制语句for while do-while if switch
- 神经网络系列讲解之离散型Hopfield网络
- extract-text-webpack-plugin
- Redis命令,订阅,数据类型