0
Give an iterative algorithm and loop invariant for 1+2+3+4+........+n
it must be iterative(loop)
3 odpowiedzi
+ 1
print(sum(range(n+1)))
+ 1
#if iterative implies recursive
s=lambda x: (0 if x==0 else x+s(x-int(abs(x)/x)))
#recursive
print(s(10))
0
a loop version of this algorithm won't do you well on arbitrarily big numbers (billions and up) so if the need for it arises, a pure math solution is avalible:
(1+2+3+...+n) == (n*(n+1))/2