吸血鬼数字

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

1260=21*60

1827=21*87

2187=27*81

《Thinking in Java》第四版中第四章练习10里有这样相关的一道练习,找出4位数的所有吸血鬼数字

吸血鬼数字,其实有一个性质:

如果x*y是个吸血鬼数字,那么x*y=(x+y)mod 9

证明:

令d(x)函数为整数x所有位数和,那么对于所有数x有

d(x) mod 9=x mod 9

假设x*y是吸血鬼数字。那么根据定义,有d(x*y)=d(x)+d(y),因此有:

(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

根据这个重要性质,《Thinking in Java》里给出了如下答案:

//: control/E10_Vampire.java
/****************** Exercise 10 *********************
 * A vampire number has an even number of digits and
 * is formed by multiplying a pair of numbers containing
 * half the number of digits of the result. The digits
 * are taken from the original number in any order.
 * Pairs of trailing zeroes are not allowed. Examples
 * include:
 * 1260 = 21 * 60
 * 1827 = 21 * 87
 * 2187 = 27 * 81
 * Write a program that finds all the 4-digit vampire
 * numbers. (Suggested by Dan Forhan.)
 ****************************************************/
package control;

public class E10_Vampire {
  public static void main(String[] args) {
    int[] startDigit = new int[4];
    int[] productDigit = new int[4];
    for(int num1 = 10; num1 <= 99; num1++)
      for(int num2 = num1; num2 <= 99; num2++) {
        // Pete Hartley's theoretical result:
        // If x*y is a vampire number then 
        // x*y == x+y (mod 9)
        if((num1 * num2) % 9 != (num1 + num2) % 9)
          continue;
        int product = num1 * num2;
        startDigit[0] = num1 / 10;
        startDigit[1] = num1 % 10;
        startDigit[2] = num2 / 10;
        startDigit[3] = num2 % 10;
        productDigit[0] = product / 1000;
        productDigit[1] = (product % 1000) / 100;
        productDigit[2] = product % 1000 % 100 / 10;
        productDigit[3] = product % 1000 % 100 % 10;
        int count = 0;
        for(int x = 0; x < 4; x++)
          for(int y = 0; y < 4; y++) {
            if(productDigit[x] == startDigit[y]) {
              count++;
              productDigit[x] = -1;
              startDigit[y] = -2;
              if(count == 4)
                System.out.println(num1 + " * " + num2
                  + " : " + product);
            }
          }
      }
  }
} /* Output:
15 * 93 : 1395
21 * 60 : 1260
21 * 87 : 1827
27 * 81 : 2187
30 * 51 : 1530
35 * 41 : 1435
80 * 86 : 6880
*///:~

光看答案难以理解,这里给出一个解答

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值