Problem:
 Score : 600 points    Problem Statement  There are N slimes standing on a number line.
The i -th slime from the left is at position x_i .  It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9} .  Niwango will perform N-1 operations. The i -th operation consists of the following procedures:   Choose an integer k between 1 and N-i (inclusive) with equal probability.  Move the k -th slime from the left, to the position of the neighboring slime to the right.  Fuse the two slimes at the same position into one slime.   Find the total distance traveled by the slimes multiplied by (N-1)! (we can show that this value is an integer), modulo (10^{9}+7) . If a slime is born by a fuse and that slime moves, we count it as just one slime.      Constraints   2 \leq N \leq 10^{5}  1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}  x_i is an integer.       Subtasks   400 points will be awarded for passing the test cases satisfying N \leq 2000 .         Input  Input is given from Standard Input in the following format:  N  x_1  x_2  \ldots  x_N       Output  Print the answer.        Sample Input 1 3
1 2 3      Sample Output 1 5   With probability \frac{1}{2} , the leftmost slime is chosen in the first operation, in which case the total distance traveled is 2 .  With probability \frac{1}{2} , the middle slime is chosen in the first operation, in which case the total distance traveled is 3 .  The answer is the expected total distance traveled, 2.5 , multiplied by 2! , which is 5 .        Sample Input 2 12
161735902 211047202 430302156 450968417 628894325 707723857 731963982 822804784 880895728 923078537 971407775 982631932      Sample Output 2 750927044   Find the expected value multiplied by (N-1)! , modulo (10^9+7) .

Solution (Python):
N = int(input())
x = list(map(int,input().split()))

mod = 10**9+7
inv = [0,1]
for i in range(2,N):
  inv.append(inv[mod % i]*(mod - mod//i) % mod)

fac = 1
for i in range(1,N):
    fac *= i
    fac %= mod

ans = 0
cur = 0
for i in range(1,N):
    cur += fac*inv[i]
    cur %= mod
    ans += cur*(x[i]-x[i-1])
    ans %= mod
print(ans)

Solution (Python):
n=int(input())
x=list(map(int,input().split()))
mod=10**9+7


def cmb(n,r,mod):
  if (r<0 or r>n):
    return 0
  r=min(r,n-r)
  return g1[n]*g2[r]*g2[n-r]%mod
g1=[1,1] 
g2=[1,1] 
inverse=[0,1]
for i in range(2,n+1):
  g1.append((g1[-1]*i)%mod)
  inverse.append((-inverse[mod%i]*(mod//i))%mod)
  g2.append((g2[-1]*inverse[-1])%mod)

ans=0
nn=[g1[n-1]]
tmp=g1[n-1]
for i in range(2,n):
  tmp+=g1[n-1]*pow(i,mod-2,mod)
  tmp%=mod
  nn.append(tmp)
  
for i in range(n-1):
  d=x[i+1]-x[i]
  ans+=d*nn[i]
  ans%=mod
print(ans)

Solution (Python):


def factorials_with_inv(k,mod):
    """
    0! ... k! とそれらのmod逆元を求めて返す
    """
    fac = [1]*(k+1)
    inv = [1]*(k+1)
    t = 1
    for i in range(1,k+1):
        t *= i
        t %= mod
        fac[i] = t

    t = pow(t,-1,mod)
    for i in reversed(range(1,k+1)):
        inv[i] = t
        t *= i
        t %= mod

    return fac, inv

def solve(X):
    MOD = 10**9+7
    N = len(X)-1
    DX = [b-a for a,b in zip(X,X[1:])]

    fac,inv = factorials_with_inv(N,MOD)
    res = 0
    s2 = 0
    s1 = 0
    s0 = 1

    P = fac[N]
    for k,d in enumerate(DX, start=2):
        x = s0-s1*(k-1)
        s2 = s1
        s1 = s0
        s0 = s0*k + x*(k+1) - s2
        x %= MOD
        s2 %= MOD
        s1 %= MOD
        s0 %= MOD
        res += x*P*inv[k-1]*d
        res %= MOD
    return res

if __name__ == '__main__':
    N = int(input())
    X = list(map(int,input().split()))
    print(solve(X))

Solution (Python):
N = int(input())
X = list(map(int, input().split()))
MOD = 10**9+7
S = 0
res = 0
F = 1
for i in range(1,N):
    S += pow(i,MOD-2,MOD)
    res += (X[i]-X[i-1])*S
    res%=MOD
    F*=i
    F%=MOD
print(res*F%MOD)

Solution (Python):
def ext_euc(a, b):
    if b == 0:
        return 1, 0, a
    y, x, v = ext_euc(b, a % b)
    y -= (a // b) * x
    return x, y, v


def mod_inv(a, mod):
    x, _, _ = ext_euc(a, mod)
    return x % mod


def mod_fac(a, mod):
    ret = 1
    for aa in range(1, a + 1):
        ret *= aa
        ret %= mod
    return ret


def main():
    MOD = 10**9 + 7
    N = int(input())
    X = list(map(int, input().split()))
    ans = 0
    for n in range(N - 1):
        ans += (X[N - 1] - X[n]) * mod_inv(n + 1, MOD)
    ans *= mod_fac(N - 1, MOD)
    print(ans % MOD)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  


N = I()
X = LI()
mod = 10**9+7
Y = [X[i+1]-X[i] for i in range(N-1)]

r = 1  
for i in range(1,N):
    r *= i
    r %= mod

C = [r]  
for i in range(2,N):
    C.append((C[-1]+r*pow(i,mod-2,mod)) % mod)

ans = 0
for y,c in zip(Y,C):
    ans += y*c
    ans %= mod

print(ans)

Solution (Python):
n, *x = map(int, open(0).read().split())
mod = 10 ** 9 + 7
fac = [1] * n
for i in range(1, n):
    fac[i] = fac[i - 1] * i % mod

ans = 0
p = 0

for i in range(n - 1):
    p = (p + pow(i + 1, mod - 2, mod))
    ans = (ans + p * (x[i + 1] - x[i])) % mod

print(ans * fac[n - 1] % mod)

Solution (Python):
n, *x = map(int, open(0).read().split())

mod = 10 ** 9 + 7

y = []
for i in range(n - 1):
    y.append(x[i + 1] - x[i])

fac = [1] * (n + 1)
for i in range(1, n):
    fac[i] = fac[i - 1] * i % mod

dp = [0] * n
ans = 0
p = 0

for i in range(n - 1):
    p = (p + pow(i + 1, mod - 2, mod))
    ans = (ans + p * y[i]) % mod

print(ans * fac[n - 1] % mod)

Solution (Python):
class Combination:
    def __init__(self, n_max=10**6, mod=10**9+7):
        
        self._fac, self._finv, self._inv = [0]*n_max, [0]*n_max, [0]*n_max
        self._fac[0], self._fac[1] = 1, 1
        self._finv[0], self._finv[1] = 1, 1
        self._inv[1] = 1
        self._mod = mod
        for i in range(2, n_max):
            self._fac[i] = self._fac[i - 1] * i % self._mod
            self._inv[i] = self._mod - self._inv[self._mod%i] * (self._mod // i) % self._mod
            self._finv[i] = self._finv[i - 1] * self._inv[i] % self._mod
    def com(self, n, r):
        if n < r: return 0
        if n < 0 or r < 0: return 0
        return self._fac[n] * (self._finv[r] * self._finv[n - r] % self._mod) % self._mod

    def perm(self,n,r):
        if n < r: return 0
        if n < 0 or r < 0: return 0
        return self._fac[n] * (self._finv[n-r] % self._mod) % self._mod


n = int(input())
xl = list(map(int, input().split()))
com = Combination(10**5+1)
MOD = 10**9+7



csum = 0
ans = 0
for i in range(n-1):
    diff = xl[i+1]-xl[i]
    val = com.com(n-1,i+1)*com.perm(i,i)*com.perm(n-2-i,n-2-i)
    
    csum += val
    csum %= MOD
    ans += diff*csum
    ans %= MOD

print(ans)

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))
    mod = 10**9+7
    ans = 0
    fact = 1
    for i in range(2, n):
        fact = fact*i % mod

    fact_2 = [fact]
    for i in range(2, n):
        fact_2.append((fact_2[-1] + fact * pow(i, mod-2, mod) % mod))

    for i in range(n-1):
        ans = (ans + (a[i+1]-a[i])*fact_2[i]) % mod
    print(ans % mod)


main()

Solution (Python):
import math
N=int(input())
L=list(map(int,input().split()))
a=0
mod=10**9+7
s=math.factorial(N-1)
ans=[s%mod]
for i in range(2,N):
  ans.append((ans[-1]+(ans[0]*pow(i,-1,mod)))%mod)
ans2=0
for i in range(N-1):
  ans2+=((L[i+1]-L[i])*ans[i])%mod
print(ans2%mod)

Solution (Python):
'''
研究室PCでの解答
'''
import math

import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"


def main():
    n = int(ipt())
    x = [int(i) for i in ipt().split()]
    d = [x[i+1]-x[i] for i in range(n-1)]
    k = [1]
    for i in range(1,n):
        k.append(k[-1]*i%mod)

    
    g2 = [1,1]
    inverse = [0,1] 
    for i in range(2,n+1):
        inverse.append((-inverse[mod%i]*(mod//i))%mod)
        g2.append((g2[-1]*inverse[-1])%mod)

    ans = 0
    na = 0
    for i in range(1,n):
        na = na*i+k[i-1]
        na %= mod
        ans += na*d[i-1]*k[-1]*g2[i]
        ans %= mod

    print(ans)
    return None

if __name__ == '__main__':
    main()

Solution (Python):
MOD=10**9+7
def facinv(N):
    fac,finv,inv=[0]*(N+1),[0]*(N+1),[0]*(N+1)
    fac[0]=1;fac[1]=1;finv[0]=1;finv[1]=1;inv[1]=1
    for i in range(2,N+1):
        fac[i]=fac[i-1]*i%MOD
        inv[i]=MOD-inv[MOD%i]*(MOD//i)%MOD
        finv[i]=finv[i-1]*inv[i]%MOD
    return fac,finv,inv

N=int(input())
x=list(map(int,input().split()))

fac,finv,inv=facinv(N)

Inv=0
ans=0
for k in range(N-1):
    Inv=Inv+inv[k+1]
    res=Inv*(x[k+1]-x[k])
    ans=(ans+res)%MOD
print(ans*fac[N-1]%MOD)

Solution (Python):
def examA():
    N = I()
    S = [""]*N; T = [""]*N
    for i in range(N):
        S[i],T[i] = LSI()
        T[i] = int(T[i])
    X = SI()
    ans = 0
    flag = False
    for i in range(N):
        if flag:
            ans +=T[i]
        if S[i]==X:
            flag = True
    print(ans)
    return

class combination():
    
    def __init__(self, n, mod):
        self.n = n
        self.fac = [1] * (n + 1)
        self.inv = [1] * (n + 1)
        for j in range(1, n + 1):
            self.fac[j] = self.fac[j - 1] * j % mod

        self.inv[n] = pow(self.fac[n], mod - 2, mod)
        for j in range(n - 1, -1, -1):
            self.inv[j] = self.inv[j + 1] * (j + 1) % mod

    def comb(self, n, r, mod):
        if r > n or n < 0 or r < 0:
            return 0
        return self.fac[n] * self.inv[n - r] * self.inv[r] % mod

def examB():
    N = I()
    X = LI()
    B = [1]*N
    for i in range(1,N-1):
        B[i+1] =B[i]*(i+1)
        B[i+1] %= mod
    XL = [X[i+1]-X[i] for i in range(N-1)]
    C = combination(N, mod)
    """
        cumL = [0]*N
    cumL[1] = XL[0]
    for i in range(1,N):
        cumL[i+1] = cumL[i]+XL[i]
    print(cumL)
    """
    ans = 0; cur = B[-1]
    now = 0

    for i in range(N-1):
        ans += cur*XL[i]
        ans %=mod

    for i in range(1,N-1):
        now += C.comb(N-1,1+i,mod)
        ans += now*XL[i]
        ans %=mod

    print(ans)
    return
"""
4
1 3 6 7
"""
def examB2():
    N = I()
    X = LI()
    L = [0]*(N-1)
    for i in range(N-1):
        L[i] = X[i+1] - X[i]

    S = [1]*N
    for i in range(1,N):
        S[i] = S[i-1] + pow(i+1,mod-2,mod)
    C = combination(N,mod)
    cnt = 0
    for i in range(N-1):
        
        cnt += S[i]*L[i]*C.fac[N-1]%mod
        cnt %= mod
    ans = cnt
    print(ans)
    return

def examC():

    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examB2()

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    N = int(readline())
    X = list(map(int, readline().split()))

    mul_mod = [0] * N

    cur = 1
    for i in range(1, N):
        cur *= i
        cur %= MOD
    mul_mod[1] = cur

    for i in range(2, N):
        mul_mod[i] = (mul_mod[1] * pow(i, MOD - 2, MOD)) % MOD

    p = [0] * (N - 1)
    p[-1] = sum(mul_mod[1:N]) % MOD

    for i in range(2, N):
        p[-i] = p[-i + 1] - mul_mod[N - i + 1]
        p[-i] %= MOD

    ans = 0

    for i in range(N - 1):
        ans += (X[i + 1] - X[i]) * p[i]
        ans %= MOD

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
x=list(map(int,input().split()))

N = 10**6
g1 = [1, 1] 
g2 = [1, 1] 
inverse = [0, 1] 

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

kaijo=1
for i in range(n-1):
    kaijo*=n-i-1
    kaijo%=mod


ans=0
cnt=0
for i in range(n-1):
    y1,y2=x[i],x[i+1]
    sa=y2-y1
    cnt+=g1[n-1]*g2[i+1]*g1[i]
    ans+=cnt*sa
    
    ans%=mod
    


print(ans)

Solution (Python):
n=int(input())
x=list(map(int,input().split()))
mod=pow(10,9)+7

def cmb(n,r,mod):
  if (r<0 or r>n):
    return 0
  r=min(r,n-r)
  return g1[n]*g2[r]*g2[n-r]%mod
g1=[1,1] 
g2=[1,1] 
inverse=[0,1]
for i in range(2,n+1):
  g1.append((g1[-1]*i)%mod)
  inverse.append((-inverse[mod%i]*(mod//i))%mod)
  g2.append((g2[-1]*inverse[-1])%mod)
ans=0
for i in range(n-1):
  ans+=(x[n-1]-x[i])*g1[n-1]*pow(i+1,mod-2,mod)
  ans%=mod
print(ans)

Solution (Python):
MOD=10**9+7
N=int(input())
xlist=list(map(int,input().split()))

fact_nm1=1
for i in range(1,N):
  fact_nm1*=i
  fact_nm1%=MOD


answer_bunshi=0
answer_bumbo=1
inv_bunshi=0
inv_bumbo=1
for i in range(1,N):  
  inv_bunshi=(i*inv_bunshi+inv_bumbo)%MOD
  inv_bumbo=(inv_bumbo*i)%MOD
  
  
  xdiff=xlist[i]-xlist[i-1]
  term_bunshi=(xdiff*inv_bunshi)%MOD
  answer_bunshi=(answer_bunshi*inv_bumbo+term_bunshi*answer_bumbo)%MOD
  answer_bumbo=(answer_bumbo*inv_bumbo)%MOD


answer_bunshi=(answer_bunshi*fact_nm1)%MOD
answer=answer_bunshi*pow(answer_bumbo,MOD-2,MOD)
answer%=MOD
print(answer)

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
x = list(map(int, input().split()))
M = 10**9+7
p = 1
invs = [None]
v = 1
for i in range(2, n+1):
    invs.append(v)
    v += pow(i, M-2, M)
    v %= M
for i in range(1, n):
    p *= i
    p %= M
ans = 0
for i in range(n-1):
    ans += (x[i+1]-x[i]) * invs[i+1]
    ans %= M
ans *= p
print(ans%M)

Solution (Python):
import itertools
mod = 10**9 + 7
stdin = [int(_) for _ in open(0).read().split()]
N, X = stdin[0], stdin[1:]
A = [pow(i, mod - 2, mod) for i in range(N)]
D = [0] + [a - b for a, b in zip(X[1:], X[:-1])]
f = 1
for i in range(1, N):
    f *= i
    f %= mod
A = [d * f * a % mod for d, a in zip(D, list(itertools.accumulate(A)))]
print(sum(A) % mod)

Solution (Python):
MOD = 10**9 + 7

def MOD_perm(n, r):
    rtn = 1
    for _ in range(r):
        rtn *= n
        rtn %= MOD
        n -= 1
    return rtn

def MOD_inv(a):
    b = MOD
    u = 1
    v = 0
    while b > 0:
        t = a // b
        a -= t * b
        a, b = b, a
        u -= t * v
        u, v = v, u
    u = u % MOD
    if u < 0:
        u += MOD
    return u

def main():
    n = int(input())
    x = list(map(int, input().split()))
    ans = 0
    inv = 0
    perm = MOD_perm(n-1, n-1)
    for i in range(1, n):
        dif = x[i] - x[i-1]
        inv += MOD_inv(i)
        inv %= MOD
        ans += dif * perm * inv
        ans %= MOD
    print(ans % MOD)

if __name__ == "__main__":
    main()

Solution (Python):
from copy import deepcopy
n = int(input())
x = list(map(int, input().split()))
mod = 10 ** 9 + 7
c = 1
for i in range(2, n):
    c *= i
    c %= mod
c2 = deepcopy(c)
ans = 0
for i in range(n):
    ans += (x[i] - x[i - 1]) * c2
    ans %= mod
    c2 += pow(i + 1, mod - 2, mod) * c
    c2 %= mod
print(ans)

Solution (Python):
mod = 10 ** 9 + 7

N = int(input())
X = list(map(int,input().split()))

def factorial(n, mod):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
        fact %= mod
    return fact

fact = factorial(N-1, mod)
ans = 0
cnt = 0
for i in range(1, N):
    cnt += pow(i, mod - 2, mod)
    ans += (X[i] - X[i-1]) * cnt

ans *= fact
ans %= mod

print(ans)

Solution (Python):
mod = 10**9+7
N = int(input())
x = list(map(int,input().split()))

ans = 0
for j in range(1,N-1):
    ans += x[j]*j*pow(j+1,mod-2,mod)
    ans %= mod
for i in range(N-2):
    ans += x[i]*(-N+i+2)*pow(N-i-1,mod-2,mod)
    ans %= mod
for i in range(N-1):
    ans += (x[N-1]-x[i])*pow(N-1-i,mod-2,mod)
    ans %= mod

for i in range(1,N):
    ans *= i
    ans %= mod

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

MAX = 2*10**5+100
MOD = 10**9+7
fact = [0]*MAX 
inv = [0]*MAX 
finv = [0]*MAX 
fact[0] = 1
fact[1] = 1
finv[0] = 1
finv[1] = 1
inv[1] = 1
    
for i in range(2, MAX):
    fact[i] = fact[i-1]*i%MOD
    inv[i] = MOD-inv[MOD%i]*(MOD//i)%MOD
    finv[i] = finv[i-1]*inv[i]%MOD

def C(n, r):
    if n<r:
        return 0
    if n<0 or r<0:
        return 0
    return fact[n]*(finv[r]*finv[n-r]%MOD)%MOD
    
N = int(input())
x = list(map(int, input().split()))
ans = 0
acc = [0]

for i in range(N-1):
    acc.append((acc[-1]+C(N-1, i+1)*fact[i]*fact[N-1-(i+1)])%MOD)

for i in range(N-1):
    d = x[i+1]-x[i]
    ans += d*acc[i+1]
    ans %= MOD
    """
    for j in range(i+1):
        ans += d*C(N-1, j+1)*fact[j]*fact[N-1-(j+1)]
        ans %= MOD
    """
print(ans)

Solution (Python):
n = int(input())
X = list(map(int,input().split()))

delta = [X[i+1] - X[i] for i in range(n-1)]
mod = 10**9 + 7

mother = 1
for i in range(1,n):
    mother *= i
    if mother > mod:mother %= mod

total = 0
ans = 0
for i in range(n-1):
    now = (total*pow(i+1,mod-2,mod) + 1)%mod
    ans += now*delta[i]%mod
    if ans > mod: ans %= mod
    total += now
print(ans*mother%mod)

Solution (Python):

N = int(input())
X = list(map(int, input().split()))
mod = 10 ** 9 + 7
rev_sum=[0 for i in range(N+1)]

for i in range(1,N+1):
    rev_sum[i]+=rev_sum[i-1]+pow(i,mod-2,mod)
ans=0
for i in range(N-1):
    ans+=(X[i+1]-X[i])*rev_sum[i+1]
    ans%=mod
for i in range(1,N):
    ans=ans*i
    ans%=mod
print(ans)

Solution (Python):
MOD = 10 ** 9 + 7

N = int(input())
xs = list(map(int, input().split()))

from itertools import accumulate

def mulmod(a, b):
    return a * b % MOD
    
from_left = list(accumulate(range(N-1, 1, -1), mulmod))[::-1] + [1]
from_right = [1] + list(accumulate(range(1, N-1), mulmod))
count = list(accumulate([mulmod(l, r) for l, r in zip(from_left, from_right)]))

ans = 0
for i in range(N-1):
    ans += (xs[i+1] - xs[i]) * count[i]
    ans %= MOD

print(ans)

Solution (Python):


import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union

























from itertools import accumulate             





def main():
    Num = Union[int, float]
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    


    class Combinatorics:
        def __init__(self, size: int, mod: int):
            '''
            >>> c = Combinatorics(size=10, mod=10**9+7)
            >>> c.fact
            [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
            >>> c.inv
            [1, 1, 500000004, 166666668, 41666667, 808333339, 301388891, 900198419, 487524805, 831947206, 283194722]
            '''
            self.size =  size
            self.mod = mod
            self.fact = self._build_factorial(size, mod)
            self.inv = self._build_inv_factorial(size, mod)
        
        def _build_factorial(self, size:int , mod: int) -> None:
            '''
            fact_mod[i] は i! % mod を表すとする
            O(n) で fact_mod[size] まで計算結果がメモされたテーブルを構築して返す
            '''
            fact = [1] * (size + 1)
            for i in range(1, size + 1):
                fact[i] = (fact[i-1] * i) % mod
            return fact
        
        def _build_inv_factorial(self, size: int, mod: int) -> None:
            '''
            inv_fact_mod[i] は 1/i! % mod を表すとする
            O(n+lgm) で inv_fact_mod[size] まで計算結果がメモされたテーブルを構築して返す
            Note:
                [フェルマーの小定理]
                a ^ p-1 ≡ 1 (mod p)
                a ^ p-2 ≡ 1/a (mod p) (逆元)
                nCr = (n!) / ((n-r)! * r!) だが、mod p の世界ではこの分母を逆元を用いて計算しておくことが可能
            '''
            inv_fact_mod = [1] * (size + 1)
            inv_fact_mod[size] = pow(self.fact[size], mod-2, mod)    
            for i in range(size-1, -1, -1):
                inv_fact_mod[i] = (inv_fact_mod[i+1] * (i+1)) % mod    
            return inv_fact_mod
        
        def comb(self, n: int, r: int) -> int:
            '''
            nCr % mod を O(1) で計算する。
            Examples:
                >>> c = Combinatorics(size=100, mod=10**9+7)
                >>> c.comb(100, 50)
                538992043   
            '''
            numerator = self.fact[n]
            denominator = (self.inv[n-r] * self.inv[r]) % self.mod
            return (numerator * denominator) % self.mod
    

    n = ii()
    L = lmi()

    c = Combinatorics(10**5, mod)
    seq = [(c.fact[n-1] * pow(i, mod-2, mod)) % mod for i in range(1, n)]
    ac = list(accumulate(seq))

    ans = 0
    for i in range(n-1):
        tmp = (L[i+1] - L[i]) * ac[i] % mod
        ans = (ans + tmp) % mod
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):


from itertools import accumulate
Q = 10**9+7

def getFactorials(N):
    ret = [0]*(N+1)
    ret[0] = 1
    for i in range(1, N+1):
        ret[i] = ret[i-1]*i%Q
    return ret

def getInv(N):
    inv = [0] * (N + 1)
    inv[1] = 1
    for i in range(2, N + 1):
        inv[i] = (-(Q // i) * inv[Q % i]) % Q
    return inv

def getCmb(N):
    inv = getInv(N)
    nCr = [1] * (N + 1)
    for i in range(1, N + 1):
        nCr[i] = (nCr[i - 1] * (N - i + 1) * inv[i]) % Q
    return nCr


def main():
    N = int( input())
    X = list( map( int, input().split()))
    if N == 2:
        print(X[0])
        return
    factorials = getFactorials(N)
    combs = getCmb(N-1)
    accX = list( accumulate(X))
    
    ans = 0
    for i in range(N-1):
        z = X[N-1] - X[N-2-i]
        c = factorials[N-2-i]*combs[i+1]%Q*factorials[i]%Q
        ans += z*c%Q
        ans %= Q
        
        if i == N-2:
            continue
        x = (accX[N-1] - accX[i]) - (accX[N-2-i]) - z
        y = factorials[N-3-i]*combs[i+2]%Q*factorials[i]%Q
        
        ans += x*y%Q
        ans %= Q
        
    print(ans)
    
if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
x = list(map(int, input().split()))

d = [x[i+1] - x[i] for i in range(n-1)]
ans = 0
mod = 10 **9 + 7
fac = 1
for i in range(1, n):
    fac *= i
    fac %= mod

tmp = 0
for i in range(n-1):
    tmp += fac * pow(i+1, mod-2, mod)
    tmp %= mod

    ans += d[i] * tmp
    ans %= mod

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def main():
    N = int(input())
    X = list(map(int,input().split()))

    ans = 0
    fact = [1]
    for i in range(1,N):
        fact.append(fact[-1]*i%MOD)
    inv_fact = [1] * N
    inv_fact[-1] = pow(fact[N - 1],MOD - 2,MOD)
    for i in range(N - 1,0,-1):
        inv_fact[i - 1] = inv_fact[i]*i%MOD
    
    cum = 0
    for i in range(N - 1):
        cum += fact[N - 1] * inv_fact[i + 1] * fact[i] % MOD
        cum %= MOD
        ans += cum * (X[i + 1] - X[i])
        ans %= MOD
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
MOD = 10 ** 9 + 7
modinv = lambda a, mod=MOD: pow(a, mod - 2, mod)

N = int(input())
X = list(map(int, input().split()))
Acc = [X[-1] - X[i] for i in range(N - 2, -1, -1)]

fac = 1
for i in range(2, N):
    fac = (fac * i) % MOD
prob = [fac] * (N - 1)
for i in range(N - 1):
    prob[i] = (prob[i] * modinv(N - 1 - i)) % MOD

ans = 0
for i in range(N - 1):
    ans += Acc[i] * prob[i]
    ans %= MOD
print(ans)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def M(n): return ModInt(n)

class ModInt():
    def __init__(self, n):
        self.n = n

    def __add__(self, x):
        x = ModInt.xn(x)
        return ModInt((self.n+x) % mod)

    def __sub__(self, x):
        x = ModInt.xn(x)
        return ModInt((self.n-x) % mod)

    def __mul__(self, x):
        x = ModInt.xn(x)
        return ModInt((self.n*x) % mod)

    def __truediv__(self, x):
        x = ModInt.xn(x)
        return ModInt(self.n * pow(x, mod-2, mod) % mod)

    @classmethod
    def xn(cls, x):
        if isinstance(x, ModInt):
            return x.n
        return x

    def __str__(self):
        return str(self.n)

def main():
    n = I()
    xa = LI()

    m1 = M(1)
    c = [m1]
    for i in range(2, n+2):
        c.append(c[-1] + m1 / i)

    r = M(0)
    for i in range(1,n):
        t = xa[i] - xa[i-1]
        r += c[i-1] * t

    for i in range(n-1,1,-1):
        r *= i

    return r

print(main())

Solution (Python):
n = int(input())
X = list(map(int, input().split()))

def extgcd(a,b):
    r = [1,0,a]
    w = [0,1,b]
    while w[2]!=1:
        q = r[2]//w[2]
        r2 = w
        w2 = [r[0]-q*w[0],r[1]-q*w[1],r[2]-q*w[2]]
        r = r2
        w = w2
    
    return [w[0],w[1]]


def mod_inv(a,m):
    x = extgcd(a,m)[0]
    return (m+x%m)%m

total = 0
min_sekisan = 1
mod = 10 ** 9 + 7
for i in range(1, n):
    min_sekisan *= i
    min_sekisan %= mod


counter = 0
for i in range(n-1):
    counter += min_sekisan
    total -= (min_sekisan * X[i]) % mod
    min_sekisan *= i + 1
    min_sekisan *= mod_inv(i + 2, mod)
    min_sekisan %= mod
total += (X[n-1] * counter) % mod
print(total % mod)

"""
from collections import defaultdict as dd
import copy
def count(n):
    lis = [[[i for i in range(1, n + 1)], dd(int)]]
    while len(lis[0][0]) != 1:
        temp = []
        for nums, counter in lis:
            for i in range(len(nums)-1):
                new_dic = copy.deepcopy(counter)
                new_dic[nums[i]] -= 1
                new_dic[nums[i+1]] += 1
                temp.append([nums[:i] + nums[i+1:], new_dic])
        lis = temp
    return lis



total = dd(int)
for lis, dic in count(7):
    for key, val in dic.items():
        total[key] += val
print(total)
"""

Solution (Python):
N = int(input())
*x, = map(int, input().split())
MOD = 10**9+7

m = 1
for i in range(1, N):
    m *= i
    m %= MOD

va, vb = 0, 1
ans = 0

for i in range(N-1):
    d = x[i+1]-x[i]
    va = ((i+1)*va+vb)%MOD
    vb = ((i+1)*vb)%MOD
    ans += (d*va*pow(vb, MOD-2, MOD)*m)
    ans %= MOD

print(ans)

Solution (Python):
from fractions import gcd


N = int(input())
*x, = map(int, input().split())
MOD = 10**9+7

m = 1
for i in range(1, N):
    m *= i
    m %= MOD

va, vb = 0, 1
ans = 0

for i in range(N-1):
    d = x[i+1]-x[i]
    va = ((i+1)*va+vb)%MOD
    vb = ((i+1)*vb)%MOD
    ans += (d*va*pow(vb, MOD-2, MOD)*m)
    ans %= MOD

print(ans)

Solution (Python):
MOD = 10**9+7

def inv_mod(n,mod):
    inv_mod = [0]*(n+1)
    inv_mod[1] = 1
    for i in range(2,n+1):
        inv_mod[i] = mod - inv_mod[mod%i] * (mod//i ) % mod
    
    return inv_mod

n = int(input())
x = list(map(int,input().split()))

x_dif = [x2-x1 for x1,x2 in zip(x,x[1:])]

fac = 1
for i in range(1,n):
    fac *= i
    fac %= MOD

inv = inv_mod(n,MOD) 
    
ans = 0
count = 0
for i,dist in enumerate(x_dif,1):
    count += (fac * inv[i]) %MOD
    count %= MOD
    
    ans += (dist * count)%MOD
    ans %= MOD

print(ans)

Solution (Python):
import math
def powmod(x, n,mod):
  if n == 0:
   return 1
  K = 1
  while n > 1:
   if n % 2 != 0:
    K = K * x%mod
    x = x ** 2%mod
    n = (n - 1) // 2
   else:
    x = x ** 2%mod
    n = n // 2%mod

  return K * x 
def cmbmod(n, r,mod):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result = result*int(numerator[k])%mod
    return result
N=int(input())
X = list(map(int,input().split()))
T=0
mod=10**9+7
pmod=0
A=math.factorial(N-1)%mod
for i in range(1,N):
 pmod+=powmod(i, mod - 2, mod)
 T+=(X[i]-X[i-1])*pmod
 T%=mod
print((A*T)%mod)