Java程序查看水仙花数(Armstrong number)

时间:2020-01-09 10:35:26  来源:igfitidea点击:

这篇文章展示了如何在给定范围内以Java生成和显示Armstrong数字(阿姆斯特朗数(Armstrong number))。如果数字等于阿姆斯特朗数字的总和,即等于该数字的位数加到该数字的幂。

例如– 371 = 33 + 73 + 13 = 27 + 343 +1 = 371

此处的位数是3,因此每个位数都会提高到3的幂并加。由于计算得出的数字等于原始数字,因此371是阿姆斯特朗数字。

1634 = 14 + 6 4 + 34 + 44 = 1 + 1296 + 81 + 256 = 1634

显示给定范围内的阿姆斯特朗数– Java程序

import java.util.Scanner;

public class ArmstrongNumber {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter start number for displaying Armstrong numbers  - ");
    int start = sc.nextInt();

    System.out.println("Enter end number for displaying Armstrong numbers  - ");
    int end = sc.nextInt();
    System.out.print("Armstrong numbers with in " + start + " and " + end + "- ");
    for(int i = start; i <= end; i++){ 
      if(checkIfArmstrong(i)){
        System.out.print(i + " ");
      }
    }
    sc.close();
  }
  private static boolean checkIfArmstrong(int number){
    // Converting to string and calculating length
    int numLength = (number+"").length();
    int temp = number;
    int sum = 0;
    while(temp > 0 ){
      int remainder = temp % 10;
      sum = sum + (int)Math.pow(remainder, numLength);
      temp = temp/10;
    }
    if(number == sum){
      return true;
    }else{
      return false;
    }	
  }
}

输出:

Enter start number for displaying Armstrong numbers  - 
10
Enter end number for displaying Armstrong numbers  - 
10000

Armstrong numbers with in 10 and 10000- 153 370 371 407 1634 8208 9474