+ 1

How to get this output 1+2+3.......+n

3rd Oct 2016, 5:06 PM
Rohit Ratnani
Rohit Ratnani - avatar
10 Answers
+ 2
@Jayash: No, because that wouldn't make sense, as this is a divergent serie.
3rd Oct 2016, 5:16 PM
Zen
Zen - avatar
+ 2
Using a loop (the aim here is to learn loops, right?): def sumInts(n): s = 0 for i in range(1, n): s += i print(s) Using sum(): def sumInts(n): print(sum(range(1, n))) The smart way: def sumInts(n): print(n*(n+1)/2)
3rd Oct 2016, 5:27 PM
Zen
Zen - avatar
+ 1
The shortest implementation is probably to use sum if you know "n" or it's of reasonable limit; use a generator for unreasonable/infinite sequences. The latter's useful if you're printing that string. If you just need the answer then there are faster solutions, like: sum of 1..50 = 1+50 = 51 2+49 = 51 3+48 = 51 ... 25+26 = 51 or: sum(min+max)*(max/2) + the 'center' number when max is odd.
3rd Oct 2016, 6:06 PM
Kirk Schafer
Kirk Schafer - avatar
0
can you help me in taking out this output by using while loop? 1 2 3 4 5
3rd Oct 2016, 5:10 PM
Imran Gul
Imran Gul - avatar
0
Hey zen... isn't N here means to infinity
3rd Oct 2016, 5:14 PM
Jayash Pandey
Jayash Pandey - avatar
0
if u see ques though
3rd Oct 2016, 5:16 PM
Jayash Pandey
Jayash Pandey - avatar
0
@Imran Gul i=1 #starting index default 1 x=5 #ending index i<x<=9 while(i<=x): print(" "*(x-i)+str(i)+" "*(i-1)) i+=1
11th Oct 2016, 2:31 PM
Sunera
Sunera - avatar
0
@sunera thank u again
11th Oct 2016, 2:33 PM
Imran Gul
Imran Gul - avatar
0
hey you can achieve this very very easily using sum() eg: if n is given print(sum(range(n+1))) to take sum of 1+2+3+4+....+50 print(sum(range(51)))
11th Oct 2016, 2:34 PM
Sunera
Sunera - avatar
0
@sunera i have few other questions .. if u can help me?
11th Oct 2016, 2:34 PM
Imran Gul
Imran Gul - avatar