#include <bits/stdc++.h>
int read() {
  int ans = 0, c, f = 1;
  while (!isdigit(c = getchar()))
    if (c == '-') f *= -1;
  do ans = ans * 10 + c - '0';
  while (isdigit(c = getchar()));
  return ans * f;
}
const int N = 1000050;
int n, a[N];
long long S;
long long calc(long long p) {
  long long ans = 0, t = 0;
  for (int i = 0; i < n; ++i) {
    t = (t + a[i]) % p;
    ans += std::min(t, p - t);
  }
  return ans;
}
int main() {
  n = read();
  for (int i = 0; i < n; ++i) S += a[i] = read();
  if (S == 1) {
    puts("-1");
    return 0;
  }
  long long ans = 0x7fffffffffffffffLL;
  for (long long i = 2; i * i <= S; ++i)
    if (S % i == 0) {
      ans = std::min(ans, calc(i));
      while (S % i == 0) S /= i;
    }
  if (S != 1) ans = std::min(ans, calc(S));
  printf("%lld\n", ans);
}
