Java程序检查阿姆斯特朗数


在数论中,阿姆斯特朗数是一种基于模式的数字,其每个数字的总位数次幂之和等于该数字本身。因此,要检查一个数字是否为阿姆斯特朗数,首先确定数字的总位数,并将其假设为“n”。然后分离每个数字,并将它们提升到“n”的幂。在最后一步,计算每个数字的幂,并将它们全部加起来。如果我们得到的总和等于原始数字,则它是一个阿姆斯特朗数,否则不是。本文旨在解释如何在Java中检查给定数字是否为阿姆斯特朗数。

Java程序检查阿姆斯特朗数

在本节中,我们将编写两个Java程序来识别数字是否为阿姆斯特朗数。在此之前,让我们借助示例讨论问题陈述 -

示例

输入1

1634

输出

1634 is an Armstrong number

解释

1^4 + 6^4 + 3^4 + 4^4 = 1634, sum of powers and the number both are same.

输入2

525

输出

525 is not an Armstrong number 

解释

5^3 + 2^3 + 5^3 = 258, sum of powers and the number both are not same.

现在,让我们进入Java程序,以检查给定数字是否为阿姆斯特朗数。

示例1:检查阿姆斯特朗数

在以下示例中,我们将使用Scanner类从用户那里获取输入数字,并检查给定数字是否为阿姆斯特朗数。

方法

  • 首先,声明一个变量来存储数字的幂之和。

  • 然后,创建一个Scanner类的实例,以从用户那里获取整数输入。

  • 将原始输入复制到另一个变量。这是必要的,因为原始数字将在下一个while循环结束时递减到0。

  • 现在,将整数输入转换为字符串,以便我们可以使用for循环遍历数字的每个数字。

  • 使用一个while循环,该循环将在原始数字变为0之前运行。我们将在此循环中放入检查阿姆斯特朗数的逻辑。

  • 最后,检查每个数字的幂之和是否等于原始数字。

import java.util.*; public class IsArmstrong { public static void main(String[] args) { // variable to store sum of powers int sum = 0; // creating instance of Scanner class Scanner sc = new Scanner(System.in); System.out.println("Enter a number to check Armstrong number: "); // to take input number int num = sc.nextInt(); // copying the input to variable named copy int copy = num; // converting integer to string String n = Integer.toString(num); // storing the length of converted string int len = n.length(); // loop to check armstrong number while(num != 0) { int rem = num % 10; int mul = 1; for(int i = 1; i <= len; i++) { mul *= rem; } sum += mul; num /= 10; } // to print the result if(sum == copy) { System.out.println(copy + " is an Armstrong number"); } else { System.out.println(copy + " is not an Armstrong number"); } } }

输出1

Enter a number to check Armstrong number: 
525
525 is not an Armstrong number

输出2

Enter a number to check Armstrong number: 
1634
1634 is an Armstrong number

示例2:检查阿姆斯特朗数

这是另一个检查阿姆斯特朗数的示例,其中我们将在声明时初始化输入数字,而不是从用户那里获取输入。

Open Compiler
import java.util.*; public class IsArmstrong { public static void main(String[] args) { int sum = 0; int num = 153; int copy = num; System.out.println("The number defined to check Armstrong is: " + num); String n = Integer.toString(num); int len = n.length(); while(num != 0) { int rem = num % 10; int mul = 1; for(int i = 1; i <= len; i++) { mul *= rem; } sum += mul; num /= 10; } if(sum == copy) { System.out.println(copy + " is a Armstrong number"); } else { System.out.println(copy + " is not an Armstrong number"); } } }

输出

The number defined to check Armstrong is: 153
153 is an Armstrong number

结论

在本文中,我们了解了什么是阿姆斯特朗数以及如何检查给定数字是否为阿姆斯特朗数。为此,我们在Java程序中使用了while和for循环以及if-else条件。

更新于: 2024年6月21日

11K+浏览量

启动您的职业生涯

通过完成课程获得认证

开始
广告