#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y, long long p) {
  long long res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) {
      res = (res * x) % p;
    }
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
long long modInverse(long long a, long long p) { return power(a, p - 2, p); }
void gcd(long long a, long long b, long long& d, long long& u, long long& v) {
  if (b == 0) {
    d = a;
    u = 1;
    v = 0;
  } else {
    gcd(b, a % b, d, v, u);
    v -= a / b * u;
  }
}
long long Inverse(long long a, long long m) {
  a %= m;
  if (a < 0) a += m;
  long long d, u, v;
  gcd(a, m, d, u, v);
  assert(d == 1);
  u %= m;
  if (u < 0) u += m;
  return u;
}
long long gcd(long long x, long long y) {
  if (x == 0 || y == 0) {
    return max(y, x);
  }
  return gcd(y % x, x);
}
long long gcdExtended(long long a, long long b, long long& x, long long& y) {
  if (a == 0) {
    x = 0;
    y = 1;
    return b;
  }
  long long x1, y1;
  long long gcd = gcdExtended(b % a, a, x1, y1);
  x = y1 - (b / a) * x1;
  y = x1;
  return gcd;
};
int main() {
  long long n;
  scanf("%lld", &n);
  ;
  vector<long long> a;
  for (long long i = 0; i < n; i++) {
    long long x;
    scanf("%lld", &x);
    a.push_back(x);
  }
  vector<long long> sum;
  long long z = 0;
  for (long long i = 0; i < n; i++) {
    z += a[i];
    sum.push_back(z);
  }
  long long p = 2;
  long long ans = 1e18;
  while (p * p <= z) {
    if (z % p == 0) {
      while (z % p == 0) z /= p;
      long long ret = 0;
      for (long long i = 0; i < n - 1; i++) {
        ret += (min(sum[i] % p, p - sum[i] % p));
      }
      ans = min(ans, ret);
    }
    p++;
  }
  if (z != 1) {
    p = z;
    long long ret = 0;
    for (long long i = 0; i < n - 1; i++) {
      ret += (min(sum[i] % p, p - sum[i] % p));
    }
    ans = min(ans, ret);
  }
  if (ans == 1e18) ans = -1;
  cout << ans << endl;
}
