请编程找出3位整数中的所有水仙花数,即3位数的每1位数的立方相加等于该数
时间: 2023-05-15 21:05:57 浏览: 94
以下是代码实现:
```python
for i in range(100, 1000):
if i == (i // 100) ** 3 + ((i // 10) % 10) ** 3 + (i % 10) ** 3:
print(i)
```
输出结果为:
```
153
370
371
407
```
这些数字就是3位整数中的所有水仙花数。
相关问题
JAVA中所有三位数中的水仙花数
在Java中,所有的数字都是以十进制表示的,因此如果要表示水仙花数,需要先定义一个方法来计算数字的位数,并通过循环来计算每个数字的立方和,最后将它们相加,判断是否等于原始数字。
以下是一个计算三位数水仙花数的Java代码示例:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
if (isNarcissisticNumber(i)) {
System.out.println(i);
}
}
}
private static boolean isNarcissisticNumber(int n) {
int sum = 0;
int count = getCount(n);
int temp = n;
while (temp > 0) {
int digit = temp % 10;
sum += Math.pow(digit, count);
temp /= 10;
}
return sum == n;
}
private static int getCount(int n) {
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
return count;
}
}
```
在上面的代码中,我们使用了一个for循环来遍历所有三位数,并且通过isNarcissisticNumber()方法来判断是否是水仙花数。isNarcissisticNumber()方法接受一个整数作为参数,它首先调用getCount()方法来计算该整数的位数,然后使用while循环来计算该整数每个数字的立方和,并将结果存储在sum变量中。最后,它将sum与原始数字进行比较,如果相等,则返回true,否则返回false。
在getCount()方法中,我们使用一个while循环来计算一个数字的位数,并将结果存储在count变量中。
以上是计算三位数水仙花数的Java代码示例,你可以根据需要进行修改来计算其他位数的水仙花数。
Python打印出所有的水仙花数并判断输入的一个三位数是不是水仙花数
水仙花数是指一个三位数,其各位数字立方和等于该数本身。下面是Python代码实现:
```python
# 打印出所有的水仙花数
for i in range(100, 1000):
num = str(i)
if int(num[0])**3 + int(num[1])**3 + int(num[2])**3 == i:
print(i)
# 判断输入的一个三位数是不是水仙花数
num = input("请输入一个三位数:")
if len(num) == 3 and int(num[0])**3 + int(num[1])**3 + int(num[2])**3 == int(num):
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
```
其中,`range(100, 1000)` 表示从 100 开始到 999 结束,因为三位数的范围是从 100 到 999。`num = str(i)` 将整数转换成字符串,方便后面取出各位数字进行立方运算。`int(num[0])**3 + int(num[1])**3 + int(num[2])**3 == i` 表示将各位数字立方后相加,判断是否等于原数。对于输入的三位数,需要先判断其长度是否为 3,然后再判断各位数字立方和是否等于原数。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.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)