java編程——吸血鬼數字(四位)__編程

來源:互聯網
上載者:User


轉載: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) {                       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.