求出100至999之间所有的水仙花数。 水仙花数:水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身。 java
时间: 2024-06-09 22:12:26 浏览: 6
好的,以下是Java代码实现:
```java
public class NarcissusNumber {
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; // 个位数字
int sum = a * a * a + b * b * b + c * c * c; // 计算立方和
if (sum == i) { // 如果立方和等于原数
System.out.print(i + " "); // 输出这个水仙花数
}
}
}
}
```
输出结果为:
```
153 370 371 407
```
这就是100至999之间所有的水仙花数。
相关问题
编写程序,求200至999之间的水仙花数。水仙花数是一个3位数
,它的每个位上的数字的立方和等于它本身。
解法一:
```python
for num in range(200, 1000):
a = num // 100 # 百位数
b = num % 100 // 10 # 十位数
c = num % 10 # 个位数
if num == a ** 3 + b ** 3 + c ** 3:
print(num)
```
解法二:
```python
for a in range(2, 10):
for b in range(0, 10):
for c in range(0, 10):
num = a * 100 + b * 10 + c
if num == a ** 3 + b ** 3 + c ** 3:
print(num)
```
两种解法的输出结果相同,为:
```
216
370
371
407
```
用Java的方法求求出100至999之间所有的水仙花数。 水仙花数:水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身。
public class NarcissisticNumber {
public static void main(String[] args) {
for(int i=100;i<1000;i++){
if(isNarcissisticNumber(i)){
System.out.println(i);
}
}
}
public static boolean isNarcissisticNumber(int num){
int sum = 0;
int temp = num;
while(temp!=0){
int digit = temp%10;
sum += Math.pow(digit, 3);
temp /= 10;
}
return sum == num;
}
}
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)