nhtrnm
nhtrnm

Reputation: 1617

Sum from 1 to n in one line Python

Given number n, I need to find the sum of numbers from 1 to n. Sample input and output:

100
5050

So I came up with print(sum(range(int(input())+1))) which solves the problem in one line but takes a long time since it's O(n). Clearly, if we know the number n then the answer can be given in one line too: print(n * (n+1) / 2) but how to replace n with input() to still make program work?

Upvotes: 1

Views: 6227

Answers (2)

怀春춘
怀春춘

Reputation: 307

Python 3, one line, and shorter than the currently accepted answer:

n=int(input());print(n*(n+1)/2)

Upvotes: 1

RemcoGerlich
RemcoGerlich

Reputation: 31270

Act as if it's Javascript; create a function that takes a parameter n, then immediately call it with the result of input():

(lambda n: n * (n + 1) / 2)(int(input()))

Upvotes: 11

Related Questions