5 ms·
Nope, that ends up with $100 too much. The proper way is documented here: <http://wiki.answers.com/Q/What_is_the_sum_of_the_first_100_positive_integers> http://
by unwind 17y ago
Nope, that ends up with $100 too much. The proper way is documented here: <http://wiki.answers.com/Q/What_is_the_sum_of_the_first_100_positive_integers> http://wiki.answers.com/Q/What_is_the_sum_of_the_first_100_p....
One way of computing it in Python, using a loop approach like you did, is like so:
sum = 0
for p in xrange(101):
sum += p
print (sum)
This uses better variable names, and a simpler looping construct. The reason for the 101 is because it starts at 0.
- colbyolson 17y agoVery neat, thank you for your reply. I knew of the shortcut to increment a variable, but I had no idea you didn't have to declare one for a loop. I also didn't not know of xrange, I will have to look that one up.
- jacquesm 17y agoShouldn't that be print ((n-1)*n)/2
- jeroen 17y agoThat's not entirely right. It should be: print ((n+1)*n)/2 (fold the sequence in half, which gives you 100 + 1 on one end and 50 + 51 on the other.)
- jacquesm 17y agoAh right, sure. I took the 'n' to be the 100, not the 101. A little too quick on the submit there, I should have run it :) But anyway, that seems to be a damn sight faster than to run a loop to add a bunch of numbers in a fixed interval. Especially for large 'n'.
- jeroen 17y agoProbably much faster, but also doing half the work yourself. It'll depend on the situation which is the better solution.
- derwiki 17y agoyou could use a list comprehension to do the same thing: print sum([x for x in xrange(101)]) although the n(n+1)/2 is probably the best, I'd just like to point that out because I wish someone would have pointed out list comprehensions to me earlier :)