![](/img/trans.png)
[英]python program, Write a program to print first x terms of the series 3N + 2 which are not multiples of 4
[英]Python program to compute the sum of the terms of the series: 1 + 2 + 4 + 8 + 16 + 32 + 64 + .... + n, where n is an input
n = int(input("Enter n: "))
total = 0
for j, i in enumerate(range(4, n + 4, 4)):
if j % 2 == 1:
i = -i
total += i
print()
print("The sum is: %s"%(total))
可以使用与此代码相同的格式:例如,如果 n = 256,程序将对 1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 求和并显示结果 511
假设n
是 2 的幂,
print(2*n - 1)
这是一个 python 解决方案:
sum(2**x for x in range(1 + int(math.log(n, 2))))
这是一个numpy
解决方案:
np.sum(2**np.arange(1 + np.log2(n)))
这是一个itertools
解决方案:
sum(2**x for x in itertools.islice(itertools.count(), 1 + int(math.log(n, 2))))
在你的系列中,下一项 = 上一项 * 2,所以要找到这个系列的总和,我们可以跟踪上一项。
n=int(input("Enter n: "))
previous_term=1
total=0
while(previous_term<=n):
total=total+previous_term
previous_term=previous_term*2
print("The sum is: %s"%(total))
def main(number=2): Final = [0] for i in range(10): Final.append(number << i) print(Final) main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.