Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of the integers from 1 to n

Tags:

python

I'm trying to write a program to add up number from 1 to n. I've managed to get it to print the numbers several times but not add them all. It keeps on just adding two of the numbers.

My 1st attempt is:

def problem1_3(n):
    my_sum = 0
    # replace this pass (a do-nothing) statement with your code
    while my_sum <= n:
        my_sum = my_sum + (my_sum + 1)
    print() 
    print(my_sum)

How can I fix this problem?

like image 995
mabski Avatar asked May 10 '17 19:05

mabski


3 Answers

I don't understand why everyone keeps making everything complex. Here is my simple solution

n = int(input())
print(n * (n + 1) // 2)
like image 74
Akshat Tamrakar Avatar answered Nov 07 '22 09:11

Akshat Tamrakar


You can do it with one line, where you create a list of integers from 0 to n and sums all the elements with sum function

def problem1_3(n):
    return sum(range(n+1))
like image 14
Guillaume Jacquenot Avatar answered Nov 07 '22 10:11

Guillaume Jacquenot


That's where I use "math" to solve problems like this. There is a formula for solving this problem: n * (n+1) / 2.

The code I would write:

def sum(n):
  return n*(n+1)//2
like image 4
ahmedg Avatar answered Nov 07 '22 11:11

ahmedg