Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def sum_of_numbers(start_number, end_number):
- # n self explanatory
- n = abs(end_number - start_number) + 1
- # n / 2 represents the number of pairs,
- # end_number+start_number
- represents the total for each pair.
- return (end_number + start_number) * (n / 2)
- def sum_of_odds(start_number, end_number):
- """ start_number < end_number, start_number and end_number are odd """
- # When adding odd numbers (1 + 3 + 5 + 7 + ....... + 2n-1)
- # you will get (1, 4, 9, 16,.......,n**2), the total can be represented as
- # n**2, in order to find the total of the first, lets say 100 numbers,
- # we use 100/2**2(half even and half odd) which is 2500, it works!
- # To make this a-bit more general, lets say we want to find the odd
- # numbers from 5 to 11, its like adding the whole thing which is 6**2 and
- # the we subtract the first 2 odd numbers ( 6**2 - 1 - 3)
- start_number_position = (start_number + 1) / 2
- end_number_position = (end_number + 1) / 2
- return (end_number_position)**2 - (start_number_position - 1)**2
- def sum_of_evens(start_number, end_number):
- """start_number < end_number, start_number and end_number are even"""
- # To find even numbers total between 2 numbers, (e.g : 12->20)
- # We add the odd numbers before each even number (11+13+15+17+19) then we
- # add 1 for each number (1*5)
- return sum_of_odds(start_number-1, end_number-1)
- + (end_number - start_number)/2 + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement