+ 1

Take a number N as input and output the sum of all numbers from 1 to N (including N).

N = int(input()) numbers = list(range(1, N)) for i in numbers: i = ((N)*(N+1))/2 print(i) """ Take a number N as input and output the sum of all numbers from 1 to N (including N). This is working code. However, since the range does not include last component, I supposed it would be N+1 to solve the problem. Why ,in the second line, when I write N+1 in range tells it is wrong? Should not it be correct? """

15th Jul 2021, 6:37 PM
Oğuz
Oğuz - avatar
5 Respuestas
+ 1
N = int(input()) i = N*(N+1)/2 print(i) ''' With the extra for loop of yours, you are computing the "sums of sum of N numbers." n*(n+1)/2 is the direct mathematical formula for finding the sum of N numbers. However, if you want to utilize a for loop then: N = int(input()) i = 0 for a in range(N): i += a print(i) Or a pythonic way: N = int(input()) print(sum([a for a in range(N)]) '''
15th Jul 2021, 6:46 PM
minirkk
minirkk - avatar
0
First of all you don't need a loop here if you are going to use that equation. Second output remains same even if you add 1 or 20 or any other number to N at second line(only number of loops will increase that way )
15th Jul 2021, 6:56 PM
Abhay
Abhay - avatar
0
# range(a, b) does not include b, thus you need to use b+1 to include b in the range, in my case n = N +1 # first stage: create the range 0 to n #second stage: convert it into a list #third stage: use the 'sum()' function to add the numbers inside the list N = int(input()) n = N+1 print(sum(list(range(0,n))))
4th Aug 2022, 7:38 PM
Alex ~ G
Alex ~ G - avatar
0
N = int(input()) numbers = list(range(1, N)) for i in numbers: i = int(((N)*(N+1))/2) print(i)
20th Sep 2022, 8:56 AM
Art3mis
Art3mis - avatar
0
C# solution using System; public class Program { static void Main(string[] args) { int num = Convert.ToInt32(Console.ReadLine()); int i=0,f=0; //your code goes here while(i<=num){ f=f+i; i++; } Console.WriteLine(f); } }
3rd Apr 2023, 1:51 PM
Esraa Salah Ali