用Java求水仙花数
时间: 2023-09-10 12:15:16 浏览: 44
水仙花数是指一个n位数(n>=3),其每个位上数字的n次幂之和等于它本身,例如153=1³+5³+3³。下面是Java代码实现:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
for(int i = 100; i < 1000; i++) {
int unitsDigit = i % 10;
int tensDigit = i / 10 % 10;
int hundredsDigit = i / 100;
int sum = (int)Math.pow(unitsDigit, 3) + (int)Math.pow(tensDigit, 3) + (int)Math.pow(hundredsDigit, 3);
if(sum == i) {
System.out.println(i + " is a narcissistic number.");
}
}
}
}
```
这个程序会输出所有的三位水仙花数。
相关问题
java 求水仙花数
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。例如:1^3 + 5^3 + 3^3 = 153。以下是 Java 代码实现:
```
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
int a = i / 100;
int b = i / 10 % 10;
int c = i % 10;
if (a * a * a + b * b * b + c * c * c == i) {
System.out.println(i);
}
}
}
}
```
使用Java求水仙花数
以下是使用 Java 语言求解水仙花数的代码:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
int num, sum, temp;
System.out.println("水仙花数有:");
for (int i = 100; i < 1000; i++) {
num = i;
sum = 0;
while (num != 0) {
temp = num % 10;
sum += temp * temp * temp;
num /= 10;
}
if (sum == i) {
System.out.print(i + " ");
}
}
}
}
```
运行结果:
```
水仙花数有:
153 370 371 407
```
代码中,我们使用 for 循环遍历 100 到 999 之间的所有三位数,然后将每个数的各位数字的立方和计算出来,最后判断是否等于该数本身,如果是,则输出该数,否则继续循环。