require "prime"

n, m = gets.chomp.split.map(&:to_i)
weight = gets.chomp.split.map(&:to_i)
pd1 = Prime.prime_division n
pd2 = Prime.prime_division m
h = Hash.new(0)
[pd1, pd2].each{|pd| pd.each{|p, n| h[p] = n if h[p] < n}}
lcm = 1
h.each{|k, v| lcm *= (k ** v)}
i = j = sum = 0
min, max = 100, 0
lcm.times{
    min = weight[i] if min > weight[i]
    max = weight[i] if max < weight[i]
    if j == m - 1
        sum += (max - min)
        min, max = 100, 0
    end
    i = (i + 1) % n
    j = (j + 1) % m
}
puts sum
