Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def sum_till_n(n):
- """
- Returns the sum of the first n natural numbers till n
- Arguments:
- n -- the number till which sum is to be returned
- >>> sum_till_n(1)
- 1
- >>> sum_till_n(10)
- 55
- >>> sum_till_n(99)
- 4950
- """
- return (n * (n + 1)) /2
- def sum_squares_till_n(n):
- """
- Returns the sum of squares of the first n natural numbers till n
- Arguments:
- n -- the number till which sum is to be returned
- >>> sum_squares_till_n(1)
- 1
- >>> sum_squares_till_n(10)
- 385
- >>> sum_squares_till_n(99)
- 328350
- """
- return (n * (n + 1) * (2*n + 1)) /6
- def sum_cubes_till_n(n):
- """
- Returns the sum of cubes of the first n natural numbers till n
- Arguments:
- n -- the number till which sum is to be returned
- >>> sum_cubes_till_n(1)
- 1
- >>> sum_cubes_till_n(10)
- 3025
- >>> sum_cubes_till_n(99)
- 24502500
- """
- t = sum_till_n(n)
- return (t * t)
- def sum_powers_till_n(n, p):
- """
- Returns the sum of passeed power of the first n natural numbers till n
- Arguments:
- n -- the number till which sum is to be returned
- p -- the power which needs to be summed for first n natural numbers
- >>> sum_powers_till_n(1, 10)
- 1
- >>> sum_powers_till_n(10, 2)
- 385
- >>> sum_powers_till_n(99, 3)
- 24502500
- """
- count = 1
- t = 0
- while count <= n:
- t = t + power(count, p)
- count = count + 1
- return t
- # Sum of first n terms of arithmetic progression
- # with a:first term and d:common difference
- def sum_of_arithmetic_progression(n, a, d):
- return (n * (2*a + (n-1)*d)) / 2
- # Sum of first n terms of geometric progression
- # with a:first term and r:common ratio
- def sum_of_geometric_progression(n, a, r):
- return (a * (1 - pow(r, n))) / (1 - r)
- def power(a, n):
- res = 1
- while n != 0:
- if (n % 2) == 1:
- res = res * a
- a = a * a
- n = n / 2
- return res
- if __name__ == '__main__':
- import doctest
- doctest.testmod()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement