编写水仙数
时间: 2023-08-03 13:08:32 浏览: 49
水仙数是指一个 n 位数 (n≥3),它的每个位上的数字的 n 次幂之和等于它本身。例如,153 是一个水仙数,因为 1³+5³+3³=153。
以下是 Python 代码实现水仙数的判断:
```python
def is_armstrong_number(n):
# 将整数转换为字符串并计算位数
num_str = str(n)
num_digits = len(num_str)
# 计算每个数字的 n 次幂之和
sum_of_powers = 0
for digit in num_str:
sum_of_powers += int(digit) ** num_digits
# 判断是否为水仙数
if sum_of_powers == n:
return True
else:
return False
```
你可以调用这个函数并传入一个整数来判断它是否为水仙数,例如:
```python
print(is_armstrong_number(153)) # 输出 True
print(is_armstrong_number(370)) # 输出 True
print(is_armstrong_number(9474)) # 输出 True
print(is_armstrong_number(9475)) # 输出 False
```
相关问题
python编写水仙花数
Python编写水仙花数可以使用循环和条件语句来实现。可以按照以下步骤进行编写:
1. 使用for循环遍历100到999之间的所有三位数。
2. 将每个数字转换为字符串,并分离出每个数字。
3. 计算每个数字的立方和。
4. 判断立方和是否等于该数字本身,如果是,则输出该数字。
下面是一个示例代码:
```
for i in range(100, 1000):
num_str = str(i)
a = int(num_str[0])
b = int(num_str[1])
c = int(num_str[2])
if a**3 + b**3 + c**3 == i:
print(i)
```
这段代码会输出所有的三位水仙花数。如果要求其他位数的水仙花数,只需要修改循环的范围即可。
scala编写水仙花数
下面是使用 Scala 编写的水仙花数程序:
```scalaobject NarcissisticNumber {
def main(args: Array[String]): Unit = {
val n = 3 // 水仙花数的位数
(i <- math.pow(, n - 1).toInt until math.pow(, n).toInt) {
val sum = i.toString.map(c => math.pow(c.asDigit, n).toInt).sum
if (sum == i) println(i)
}
}
}
```
在这个程序中,我们使用了 Scala 的 map、sum 等函数式编程特性,将水仙花数的计算过程写得更加简洁和优雅。值得注意的是,我们使用了 `math.pow` 函数来计算数字的幂次方,以及 `c.asDigit` 来将字符转换为数字。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)