How to Sum of the First N Positive Integers in Python

How to Sum of the First N Positive Integers in Python

T3SO Tutorials

5 лет назад

63,457 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

عصر الاستيقاظ
عصر الاستيقاظ - 02.06.2023 01:36

I used my logic and I got this different code with same results :

N = int(input("N = "))
sum = N
for n in range(1, N):
sum += (N - n)
print("sum =", sum)

the code work like this:
sum=N+(N-1)+(N-2)+...+(N-N)
if N=3 then
sum= 3 + (3-1) + (3-2) + (3-3) = 3+2+1+0 = 6

Ответить
Learning Bigdata
Learning Bigdata - 15.05.2023 16:33

You mentioned N positive numbers and so the below code takes N inputs and calculates only the positive numbers:

usr_input = int(input("How many positive integers do you want to calculate the sum for: "))
total_sum = 0

for i in range(usr_input):
num = int(input(f"Enter positive integer {i+1}: "))
if num > 0:
total_sum += num

print(total_sum)

Ответить
Taha Anass
Taha Anass - 02.03.2023 23:41

I think i should wach this , it really nice , thanks for your videos ! Keep going !

Ответить
CodeX
CodeX - 31.12.2022 16:57

n = int(input())
sum = 0
for x in range(1, n+1):
sum+=x
print(sum)
Correct?????

Ответить
Debayan Mandal
Debayan Mandal - 11.07.2022 19:50

Great logic 💖💖💖

Ответить
Ramesh M
Ramesh M - 02.09.2021 00:28

Why are we using n*(n+1)/2? Can anyone explain me little 🥺

Ответить
Anubhav Singh
Anubhav Singh - 30.05.2021 18:29

class Prac:
total = 0
def __init__(self):
self.n = int(input("Enter number : "))

def avg_num(self):
sum = self.n*(self.n+1)/2
return sum
while True:
av = Prac()
if av.n<=10000:
print(av.avg_num())
else:
print("Enter number less then 10000\n")
continue

Ответить
lx
lx - 25.03.2020 04:11

n*(n+1)/2 also works, order of precedence

Ответить