吸血鬼数字

来源:互联网 发布:java工作流引擎的书本 编辑:程序博客网 时间:2024/06/09 14:21
      吸血鬼数字指的是位数为偶数的数字,可以由一对数字相乘而得到,而这对数字则各包含乘积一般位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的,例如下面的吸血鬼数字:
     1260 = 21 X 60
     1827 = 21 X 87
     2187 = 27 X 81
    下面的算法,是找出4位数的所有吸血鬼数字。
     我们假设一个吸血鬼数字 value = 1000a+100b+10c+d,两个乘数为
     1.x = 10a+b,y=10c+d,则value - x -y=990a+99b=99(10a+b);
     2.x = 10a+c,y=10b+d,则value - x -y=990a+90b+9c=9(110a+10b+c);
     3.x = 10a+d,y=10b+c,则value - x -y=990a+90b+9c=9(10a+b+c);
    可以看出四位数的吸血鬼数字满足条件:(value - x -y)%9=0
所以整个算法如下:
public class Example {
 public static void main(String[] args) {
  int[] r1 = new int[4];
  int[] r2 = new int[4];
  for (int x = 10; x < 100; x++) {
   for (int y = x + 1; y < 100; y++) {
    int result = x * y;
    if (result < 1000 || result % 100 == 0 ||(result - x - y) % 9 != 0) {
     continue;
    }
    r1[0] = x / 10;
    r1[1] = x % 10;
    r1[2] = y / 10;
    r1[3] = y % 10;
    r2[0] = result / 1000;
    r2[1] = (result % 1000) / 100;
    r2[2] = ((result % 1000) % 100) / 10;
    r2[3] = ((result % 1000) % 100) % 10;
    Arrays.sort(r1);
    Arrays.sort(r2);
    if (r1[0] == r2[0] && r1[1] == r2[1] && r1[2] == r2[2]
      && r1[3] == r2[3]) {
     System.out.println(result + "=" + x + "*" + y);
    }
   }
  }
 }
}
    得到的结果为:
    1395=15*93
    1260=21*60
    1827=21*87
    2187=27*81
    1530=30*51
    1435=35*41
    6880=80*86
  
0 0
原创粉丝点击