概述
在数论中,水仙花数(Narcissistic number),也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number) ,用来描述一个N位非负整数,其各位数字的N次方和等于该数本身。
举例
例如153、370、371及407就是三位超完全数字不变数,其各个数之立方和等于该数:
- 153 = 13 + 53 + 33。
- 370 = 33 + 73 + 03。
- 371 = 33 + 73 + 13。
- 407 = 43 + 03 + 73。
Java算法
1 /**
2 * A Narcissistic number is a number that is the sum of its own digits each
3 * raised to the power of the number of digits. E.g., 0, 1, 2, 3, 4, 5, 6, 7, 8,
4 * 9, 153, 370, 371, 407, 1634, 8208, 9474.
5 */
6 public class NarcissisticNumberExample {
7 //判断value是否为水仙花数
8 public static boolean isNarcissisticNumber(int value) {
9 int temp = value;
10 int digits = 0;
11 //判断value有几位数,保存在digits
12 while (temp > 0) {
13 digits++;
14 temp /= 10;
15 }
16 temp = value;
17 int sum = 0;
18 while (temp > 0) {
19 sum += Math.pow(temp % 10, digits);
20 temp /= 10;
21 }
22 return sum == value;
23 }
24
25 //开始数和结束数
26 public static void printNarcissistics(int from, int to) {
27 int which=0;
28 for (int i = from; i <= to; i++)
29 if (isNarcissisticNumber(i)){
30 which++;
31 System.out.println("第"+which+"个水仙数是:"+i);
32 }
33
34
35 }
36
37 //1000里有几个水仙数
38 public static void main(String[] args) {
39 printNarcissistics(0,1000);
40 }
41
42 }
结果
第1个水仙数是:0
第2个水仙数是:1
第3个水仙数是:2
第4个水仙数是:3
第5个水仙数是:4
第6个水仙数是:5
第7个水仙数是:6
第8个水仙数是:7
第9个水仙数是:8
第10个水仙数是:9
第11个水仙数是:153
第12个水仙数是:370
第13个水仙数是:371
第14个水仙数是:407
参考链接:
维基百科:https://zh.wikipedia.org/wiki/%E6%B0%B4%E4%BB%99%E8%8A%B1%E6%95%B0
Java for Beginners-Narcissistic Number: http://primaryjava.blogspot.hk/2013/10/narcissistic-number.html
来源:https://www.cnblogs.com/JumperMan/p/6684040.html