可以使用循环来求1到n的和,也可以使用数学公式来直接计算。
方法一:循环求和
def sum_of_numbers(n):total = 0for i in range(1, n+1):total += ireturn totaln = int(input("请输入一个整数n:"))result = sum_of_numbers(n)print("1到{}的和为:{}".format(n, result))
方法二:数学公式求和
def sum_of_numbers(n):return (1 + n) * n // 2n = int(input("请输入一个整数n:"))result = sum_of_numbers(n)print("1到{}的和为:{}".format(n, result))
这两种方法都可以得到1到n的和,区别在于方法一是通过循环累加求和,复杂度为O(n),而方法二是使用数学公式求和,复杂度为O(1),所以方法二更为高效。