Advertisement
karlakmkj

sum of first n numbers (natural nos.)

May 25th, 2021
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. # Using while loop as we don't know the number input
  2. # increasing method 1 + 2 + 3 + 4 + ...
  3. def find_sum(n):
  4.     x = 1 #start with 1
  5.     sum = 0
  6.     while x <= n: #until x reaches the number n
  7.         sum += x
  8.         x +=1
  9.     return sum
  10.  
  11. # shortcut method using formula
  12. def find_sum(n):
  13.     return n*(n+1)/2
  14.  
  15. # decreasing method ... + 4 + 3 + 2 + 1
  16. def find_sum(n):
  17.     sum = 0
  18.     while n > 0: # until n reaches 1
  19.         sum +=n
  20.         n -= 1  # decrement of n by 1
  21.     return sum
  22.  
  23. print(find_sum(15))
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement