
object Main extends App {

  import scala.io.StdIn._
  import scala.math._


  val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
  val a = readLine.trim.split(' ').map(_.toInt)
  val g = gcd(n, m)
  println(
    (0 until n / g).map{start ⇒ (0 until m).map(diff ⇒ a((start * g + diff) % n)).let{it ⇒ it.max - it.min}}.sum
  )

  def gcd(a: Int, b: Int): Int = {
    b match {
      case 0 ⇒ a
      case _ ⇒ gcd(b, a % b)
    }
  }
  implicit class Extension[T](val value :T){
    def also(func: T ⇒ Unit): T = {
      func(value)
      value
    }
    def let[R](func: T ⇒ R): R = func(value)
  }
}
