1.编写程序求全部水仙花数。所谓水仙花数是指一个三位数,其各位数字立方的和等于该数。2.编写程序求1*2*3+3*4*5+…+99*100*101 表达式的值。3.编写程序求斐波那契数列第n项的值,并输出该数列。运行结果
时间: 2024-10-14 10:11:53 浏览: 27
“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身
5星 · 资源好评率100%
1. 求解水仙花数的程序示例(Python):
```python
def is_armstrong_number(num):
# 将数字转换成字符串并获取每一位数字
digits = [int(digit) for digit in str(num)]
# 计算每位数字的立方和
sum_of_cubes = sum([digit ** 3 for digit in digits])
# 如果和等于原数,那么它是水仙花数
return num == sum_of_cubes
for i in range(100, 1000): # 遍历三位数范围
if is_armstrong_number(i):
print(f"{i} 是水仙花数")
```
2. 计算表达式1*2*3 + 3*4*5 + ... + 99*100*101的值(Python):
```python
total = sum(i * (i + 1) * (i + 2) for i in range(1, 101))
print(f"表达式的值为: {total}")
```
3. 斐波那契数列第n项的递归和非递归实现(Python):
**递归方法:**
```python
def fibonacci_recursive(n):
if n <= 0:
return "输入错误"
elif n == 1 or n == 2:
return 1
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
n = int(input("请输入斐波那契数列的项数: "))
result = fibonacci_recursive(n)
print(f"第{n}项的值是: {result}")
```
**非递归方法(使用动态规划):**
```python
def fibonacci_iterative(n):
if n <= 0:
return "输入错误"
fib_sequence = [0, 1]
for _ in range(2, n + 1):
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[n]
n = int(input("请输入斐波那契数列的项数: "))
result = fibonacci_iterative(n)
print(f"第{n}项的值是: {result}")
```
阅读全文