+ 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? """
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)])
'''
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 )
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))))
0
N = int(input())
numbers = list(range(1, N))
for i in numbers:
i = int(((N)*(N+1))/2)
print(i)
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);
}
}