轉載:http://blog.csdn.net/tianmijieguo/article/details/46400911
從《Thinking in Java》(中文第四版)中第4章的練習10看到“吸血鬼數字”,特編程實現,以下為3種演算法(針對四位元的)及其對比:
首先解釋一下吸血鬼數字:吸血鬼數字是指位元為偶數的數字,可由一對數字相乘而得到,這對數字各包含乘積的一半位元的數字,以兩個0結尾的數字是不允許的。
四位元吸血鬼數字樣本:1260=21*60,1827=21*87,2187=27*81……
先列出結果:一共7個:1260=21*60,1395=15*93,1435=41*35,1530=51*30,1827=87*21,2187=27*81,6880=86*80
方法一:
本方法是《Thinking in Java》的官方答案,由於所處章節很靠前,所以採用的遍曆四位元方法,正向思維,即先有四位元,再拆分,四個數字組合相乘,若乘積與原數相等,則輸出,並計算為一個吸血鬼數字。
[java] view plain copy public class SearchforVampireThinkinginJava { // control/VampireNumbers.java // TIJ4 Chapter Control, Exercise 10, page 154 /* 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.) */ // 本方法是順向思維,即先有四位元,再拆分,四個數字組合相乘,若乘積與原數相等,則輸出,並計算為一個吸血鬼數字。TMJG添加此行並注釋 // 其實sum的結果為107976次,非常大,演算法效率很低,並且出現了重複(6880 = 86 * 80,6880 = 80 * 86)。TMJG添加此行並注釋 static int sum=0;//記錄調用判斷的次數,TMJG添加此行並注釋 static int a(int i) { return i/1000; //求千位元字,下同,TMJG添加此行並注釋 } static int b(int i) { return (i%1000)/100; } static int c(int i) { return ((i%1000)%100)/10; } static int d(int i) { return ((i%1000)%100)%10; } static int com(int i, int j) { //形成10~99的兩位元,TMJG添加此行並注釋 return (i * 10) + j; } static void productTest (int i, int m, int n) { sum++; if(m * n == i) System.out.println(i + " = " + m + " * " + n); } public static void main(String[] args) {