+ 1
How to get this output 1+2+3.......+n
10 Answers
+ 2
@Jayash: No, because that wouldn't make sense, as this is a divergent serie.
+ 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)
+ 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.
0
can you help me in taking out this output by using while loop?
1
2
3
4
5
0
Hey zen... isn't N here means to infinity
0
if u see ques though
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
0
@sunera thank u again
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)))
0
@sunera i have few other questions .. if u can help me?