1. 程式人生 > >java:演算法 - 水仙花數

java:演算法 - 水仙花數

題目:打印出所有的"水仙花數",所謂"水仙花數"是指一個三位數,其各位數字立方和等於該數本身。例如:153是一個"水仙花數",因為153=1的三次方+5的三次方+3的三次方。
程式分析:利用for迴圈控制100-999個數,每個數分解出個位,十位,百位。

package com.oz.algorithm;
import java.util.*;

public class MyMath{
  /*
   * this function returns a list of Narcissutic Numbers
   */
  public static List<Short>
getNarcissutic(){ List<Short> narcissuList = new ArrayList<>(); short number = 100; //add narcissu to the list for(;number<=999;number++){ if( isNarcissutic(number) ) narcissuList.add(number); } return narcissuList; } /* * check if a number is a Narcissutic Number */
public static boolean isNarcissutic(short number){ short hundreds = (short)(number / 100); short tens = (short)((number - hundreds * 100) / 10 ); // or (short)(number%100)/10 short ones = (short)(number - hundreds * 100 - tens * 10); // or (short)(number%10) short sum = (short)(Math.pow(hundreds,3) +
Math.pow(tens,3) + Math.pow(ones,3)); //return true if the number is a narcissu if(sum == number) return true; else return false; } }

測試:

package com.oz;
import com.oz.algorithm.*;

public class Test1{

  public static void main(String[] args){

    System.out.print(MyMath.getNarcissutic());
    
  }

}

輸出:

[153, 370, 371, 407]

附錄:常見自冪數

三位的水仙花數共有4個:153,370,371,407;
四位的四葉玫瑰數共有3個:1634,8208,9474;
五位的五角星數共有3個:54748,92727,93084;
六位的六合數只有1個:548834;
七位的北斗七星數共有4個:1741725,4210818,9800817,9926315;
八位的八仙數共有3個:24678050,24678051,88593477

附錄摘自百度百科