Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. def sum_of_numbers(start_number, end_number):
  2.  
  3. # n self explanatory
  4. n = abs(end_number - start_number) + 1
  5.  
  6. # n / 2 represents the number of pairs,
  7. # end_number+start_number
  8. represents the total for each pair.
  9. return (end_number + start_number) * (n / 2)
  10.  
  11. def sum_of_odds(start_number, end_number):
  12. """ start_number < end_number, start_number and end_number are odd """
  13. # When adding odd numbers (1 + 3 + 5 + 7 + ....... + 2n-1)
  14. # you will get (1, 4, 9, 16,.......,n**2), the total can be represented as
  15. # n**2, in order to find the total of the first, lets say 100 numbers,
  16. # we use 100/2**2(half even and half odd) which is 2500, it works!
  17.  
  18. # To make this a-bit more general, lets say we want to find the odd
  19. # numbers from 5 to 11, its like adding the whole thing which is 6**2 and
  20. # the we subtract the first 2 odd numbers ( 6**2 - 1 - 3)
  21.  
  22. start_number_position = (start_number + 1) / 2
  23. end_number_position = (end_number + 1) / 2
  24.  
  25. return (end_number_position)**2 - (start_number_position - 1)**2
  26.  
  27. def sum_of_evens(start_number, end_number):
  28. """start_number < end_number, start_number and end_number are even"""
  29.  
  30. # To find even numbers total between 2 numbers, (e.g : 12->20)
  31. # We add the odd numbers before each even number (11+13+15+17+19) then we
  32. # add 1 for each number (1*5)
  33.  
  34. return sum_of_odds(start_number-1, end_number-1)
  35. + (end_number - start_number)/2 + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement