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
这是另一个用于检查阿姆斯特朗数的示例,不同之处在于我们将在声明的时候初始化输入的数字。
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条件。