Give an iterative algorithm and loop invariant for 1+2+3+4+........+n | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Give an iterative algorithm and loop invariant for 1+2+3+4+........+n

it must be iterative(loop)

8th Sep 2018, 1:52 AM
Suryaprakash
Suryaprakash - avatar
3 Answers
+ 1
print(sum(range(n+1)))
8th Sep 2018, 4:39 AM
Louis
Louis - avatar
+ 1
#if iterative implies recursive s=lambda x: (0 if x==0 else x+s(x-int(abs(x)/x))) #recursive print(s(10))
8th Sep 2018, 4:45 AM
Louis
Louis - avatar
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
8th Sep 2018, 10:18 AM
hinanawi
hinanawi - avatar