您的位置:首页 > 编程语言 > Java开发

找出四位数的所有吸血鬼数字(JAVA)

2016-11-08 18:52 405 查看
/**

* 找出四位数的所有吸血鬼数字

* 吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数的数字,其中从最初的数字中选取的数字可以任意排序.

* 以两个0结尾的数字是不允许的。

* 例如下列数字都是吸血鬼数字

1260=21*60

1827=21*87

2187=27*81



* 比较笨的低效率的做法: 遍历所有四位数, 每生成一个四位数的时候,

* 在双重循环遍历两位数,在两位数的内层循环中判断是否与最外层循环的四位数相等。 如果相等把这些数字都存放到数组,进行排序后比较

* 两组数字,如果相等那么输出这个数就是要找的数字;

*/

了解下这个英文参考:吸血鬼数字

An important theoretical result found by Pete Hartley:

1. If x·y is a vampire number then x·y == x+y (mod 9) Proof: Let mod be the binary modulo operator and d(x) the sum of the decimal

digits of x.

2. It is well-known that d(x) mod 9 = x mod 9, for all x.

Assume x·y is a vampire.

3.Then it contains the same digits as x and y,and in particular d(x·y) = d(x)+d(y).

4.This leads to:

(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 = (x+y) mod 9

The solutions to the congruence are (x mod 9, y mod 9) in {(0,0),

(2,2), (3,6), (5,8), (6,3), (8,5)} Only these cases (6 out of 81) have

to be tested in a vampire search based on testing x·y for different

values of x and y.

public class Exercise10 {

JAVA实现:

public static void main(String[] args) {
// TODO 自动生成的方法存根
int num1, num2, result, i, j,
count = 0;
int[] predata = new int[4];
int[] lastdata = new int[4];

for(num1 = 10; num1 < 99; num1++)
for(num2 = num1; num2 < 99; num2++){
result = num1 *num2;
count = 0;
if(((num1 * num2) %9) !=((num1 + num2) %9))
continue;
predata[0] = num1 / 10;
predata[1] = num1 % 10;
predata[2] = num2 / 10;
predata[3] = num2 % 10;
lastdata[0] = result / 1000;
lastdata[1] = (result % 1000) / 100;
lastdata[2] = (result % 1000 % 100) / 10;
lastdata[3] = (result % 1000 % 100 % 10);
for(i = 0; i < 4 ; i++)
for(j = 0; j < 4; j++){
if(predata[i] == lastdata[j]){
count++;
predata[i] = -1;
lastdata[j] = -2;
}
}
if(count == 4)
System.out.println(num1 +" * " + num2 + " = "+ result);
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 吸血鬼数字
相关文章推荐