Advertisement
Guest User

Untitled

a guest
Jul 1st, 2015
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. def sum_till_n(n):
  2. """
  3. Returns the sum of the first n natural numbers till n
  4. Arguments:
  5. n -- the number till which sum is to be returned
  6. >>> sum_till_n(1)
  7. 1
  8. >>> sum_till_n(10)
  9. 55
  10. >>> sum_till_n(99)
  11. 4950
  12. """
  13. return (n * (n + 1)) /2
  14.  
  15.  
  16. def sum_squares_till_n(n):
  17. """
  18. Returns the sum of squares of the first n natural numbers till n
  19. Arguments:
  20. n -- the number till which sum is to be returned
  21. >>> sum_squares_till_n(1)
  22. 1
  23. >>> sum_squares_till_n(10)
  24. 385
  25. >>> sum_squares_till_n(99)
  26. 328350
  27. """
  28. return (n * (n + 1) * (2*n + 1)) /6
  29.  
  30. def sum_cubes_till_n(n):
  31. """
  32. Returns the sum of cubes of the first n natural numbers till n
  33. Arguments:
  34. n -- the number till which sum is to be returned
  35. >>> sum_cubes_till_n(1)
  36. 1
  37. >>> sum_cubes_till_n(10)
  38. 3025
  39. >>> sum_cubes_till_n(99)
  40. 24502500
  41. """
  42. t = sum_till_n(n)
  43. return (t * t)
  44.  
  45. def sum_powers_till_n(n, p):
  46. """
  47. Returns the sum of passeed power of the first n natural numbers till n
  48. Arguments:
  49. n -- the number till which sum is to be returned
  50. p -- the power which needs to be summed for first n natural numbers
  51. >>> sum_powers_till_n(1, 10)
  52. 1
  53. >>> sum_powers_till_n(10, 2)
  54. 385
  55. >>> sum_powers_till_n(99, 3)
  56. 24502500
  57. """
  58. count = 1
  59. t = 0
  60.  
  61. while count <= n:
  62. t = t + power(count, p)
  63. count = count + 1
  64.  
  65. return t
  66.  
  67. # Sum of first n terms of arithmetic progression
  68. # with a:first term and d:common difference
  69. def sum_of_arithmetic_progression(n, a, d):
  70. return (n * (2*a + (n-1)*d)) / 2
  71.  
  72. # Sum of first n terms of geometric progression
  73. # with a:first term and r:common ratio
  74. def sum_of_geometric_progression(n, a, r):
  75. return (a * (1 - pow(r, n))) / (1 - r)
  76.  
  77. def power(a, n):
  78. res = 1
  79.  
  80. while n != 0:
  81. if (n % 2) == 1:
  82. res = res * a
  83.  
  84. a = a * a
  85. n = n / 2
  86.  
  87. return res
  88.  
  89. if __name__ == '__main__':
  90. import doctest
  91. doctest.testmod()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement