使用高斯方法,可以快速有效地打印一系列数字。 :)。
使用循环涉及的答案对大数字不利(例如:打印从1到1 ^ 19的数字之和)。
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 5000, 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
您怎么看?我们可以做得更好吗?