zoukankan      html  css  js  c++  java
  • 算法之水仙花数(Java语言)

    概述


    数论中,水仙花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

  • 相关阅读:
    C#Redis哈希Hashes
    C#Redis集合set
    C#Redis列表List
    C#Redis字符串
    入门redis
    C#/Net代码精简优化技巧
    单点登录在asp.net中的简单实现
    sql注入
    数据库sql优化
    常常忘记但是很重要的sql语句
  • 原文地址:https://www.cnblogs.com/JumperMan/p/6684040.html
Copyright © 2011-2022 走看看