吸血鬼數字演算法

來源:互聯網
上載者:User

標籤:pre   允許   java   解法   blog   偶數   數字   bcd   for   

吸血鬼數字是指位元為偶數的數字,可以由一對數字相乘得到,而這對數字各包含乘積一半位元的數字,其中從最初數字中選取的數字可以任意排序。以兩個0結尾的數字是不允許的。下面是一些吸血鬼數字:

15*93: 1395
21*60: 1260
21*87: 1827

寫一個程式找出4位元中的所有吸血鬼數字:

 

下列解法為Java編程思想提供的參考解法

 

 1         int[] startDigit = new int[4]; //start digit 2         int[] productDigit = new int[4];   //product digit 3         for (int num1 = 10; num1 <= 99; num1++){ 4             for (int num2 = num1; num2 <=99; num2++){ 5                 if ((num1 * num2) % 9 != (num1 + num2) % 9) 6                     continue; 7                 int product = num1 * num2; 8                 startDigit[0] = num1 / 10; 9                 startDigit[1] = num1 % 10;10                 startDigit[2] = num2 / 10;11                 startDigit[3] = num2 % 10;12                 productDigit[0] = product / 1000;13                 productDigit[1] = (product % 1000) / 100;14                 productDigit[2] = product % 1000 % 100 /10;15                 productDigit[3] = product % 1000 % 100 % 10;16                 int count = 0;17                 for (int x = 0; x < 4; x++){18                     for (int y = 0; y < 4; y++){19                         if (productDigit[x] == startDigit[y]){20                             count++;21                             productDigit[x] = -1;22                             startDigit[y] = -2;23                             if (count == 4)24                                 System.out.println(num1 + " * " + num2 + ":" + product);25                         }26                     }27                 }28             }29         }
Vampire Algorithm

 

提示:

4位吸血鬼數字形式為abcd

1000a  + 100b + 10c + d = (10a + b) + (10c + d)

1000a  + 100b + 10c + d = (10a + c) + (10b + d)

......

無論何種形式, 我們發現多項式中除了三個一位元以外都是10的倍數,所以很容易想到等式兩邊同時%9,等式仍然成立。

如果%9等式不成立,那麼這個數一定不是吸血鬼數字。

 

吸血鬼數字演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.