解法1:采用两重迭代,依次求出(1+2+3+…+i)(1≤i≤n)后累加。
解法2:采用一重迭代,利用i(i+1)/2(1≤i≤n)求和后再累加。
解法2:直接利用n(n+1)(n+2)/6公式求和。
def solve1(self):
sum_0 = 0
for i in range(1, self.n + 1):
for j in range(1, i + 1):
sum_0 += j
return sum_0
def solve2(self):
sum_0, sum_1 = 0, 0
for i in range(1, self.n + 1):
sum_1 += i
sum_0 += sum_1
return sum_0
def solve3(self):
sum_0 = self.n * (self.n + 1) * (self.n + 2) // 6
return sum_0
n = int(input("请输入n:"))
import time
class Exp2:
def __init__(self, coe):
self.n = coe
def solve1(self):
sum_0 = 0
for i in range(1, self.n + 1):
for j in range(1, i + 1):
sum_0 += j
return sum_0
def solve2(self):
sum_0, sum_1 = 0, 0
for i in range(1, self.n + 1):
sum_1 += i
sum_0 += sum_1
return sum_0
def solve3(self):
sum_0 = self.n * (self.n + 1) * (self.n + 2) // 6
return sum_0
n=50000
s=Exp2(n)
t1 = time.time() #获取开始时间
print(" 解法1 sum1=%d" %(s.solve1()))
t11 = time.time() #获取结束时间
print(" 运行时间: %ds" %(t11-t1))
t2 = time.time() #获取开始时间
print(" 解法2 sum2=%d" %(s.solve2()))
t22 = time.time() #获取结束时间
print(" 运行时间: %ds" %(t22-t2))
t3 = time.time() #获取开始时间
print(" 解法3 sum3=%d" %(s.solve3()))
t33 = time.time() #获取结束时间
print(" 运行时间: %ds" %(t33-t3))