n到n的整数对等点总和的算法

时间:2018-11-14 12:37:06

标签: algorithm sum

我知道从1到n怎么做,但是从n1到n2我找不到算法。例如:n1 = 10和n2 = 14,答案是36; n1 = 10,n2 = 6,答案是24。

2 个答案:

答案 0 :(得分:0)

对于1到n,公式为sum =n(n+1)/2,因此从n1n2,您必须计算n1-1个项的总和和n2个项的总和然后减去。

sum_of_n1_to_n2 = n2(n2+1)/2  - (n1-1)((n1-1) +1)/2;

答案 1 :(得分:0)

如果您知道如何将1与n相加,即int sumOfRange(int n1, int n2) { int n = n2 - n1; int triangle = n * (n + 1) / 2; int rectangle = n1 * n; return triangle + rectangle; } ,那就好了。

然后将差值添加到n1。

import tkinter as tk
from tkinter import ttk, filedialog

LARGE_FONT = ("Arial", 12)
MEDIUM_FONT = ("Arial", 11)
REGULAR_FONT = ("Arial", 10)

text_z = ["Select file 1", "Select the file 2", "Select file 3", "Select file 4"]

window=tk.Tk()

def click(): 
    z = tk.filedialog.askopenfilename(initialdir = "/",title = "Select file", filetypes = ( ("Excel file", "*.xlsx"), ("All files", "*.*") ) )
    a[i-2].insert(tk.END, z)
    z[i] = a[i-2].get()

##Main program
#There is an image I will add at the end on row=0
ttk.Label(window, text="file load", font = LARGE_FONT, background = "white").grid(row=1, column=1, columnspan=3, padx=20, pady = 10, sticky="W")

a = [tk.StringVar(window) for i in range(len(text_z))]

for i in range(2,len(text_z)+2): 
    Label_z = ttk.Label(window, text=text_z[i-2], background="white").grid(row= 2*i, column=0,columnspan=3, padx=10, pady=2, sticky="W")
    a[i-2] = ttk.Entry(window, width=60, background="gray")
    a[i-2].grid(row= 2*i+1, column=0, columnspan=3, padx=10, sticky="WE")
    ttk.Button(window, text="Search", width=10, command=click).grid(row= 2*i+1, column=3, padx=5, sticky="W")

window.mainloop()