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
是两个的力量,
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()