#include <bits/stdc++.h>
using namespace std;
void fastIO() {
  std::ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
template <typename T, typename U>
inline void mnze(T &x, U y) {
  if (y < x) x = y;
}
template <typename T, typename U>
inline void mxze(T &x, U y) {
  if (x < y) x = y;
}
void _scan(int &x) { scanf("%d", &x); }
void _scan(long long &x) { scanf("%lld", &x); }
void _scan(double &x) { scanf("%lf", &x); }
void _scan(char &x) { scanf(" %c", &x); }
void _scan(char *x) { scanf("%s", x); }
void scan() {}
template <typename T, typename... U>
void scan(T &head, U &...tail) {
  _scan(head);
  scan(tail...);
}
template <typename T>
void _dbg(const char *sdbg, T h) {
  cerr << sdbg << "=" << h << "\n";
}
template <typename T, typename... U>
void _dbg(const char *sdbg, T h, U... t) {
  while (*sdbg != ',') cerr << *sdbg++;
  cerr << "=" << h << ",";
  _dbg(sdbg + 1, t...);
}
long long MOD = 1e9 + 7;
inline long long Msum(long long x) { return x; }
template <typename... Rest>
inline long long Msum(long long x, Rest... rest) {
  return (x + Msum(rest...)) % MOD;
}
inline long long Mprod(long long x) { return x; }
template <typename... Rest>
inline long long Mprod(long long x, Rest... rest) {
  return x * Mprod(rest...) % MOD;
}
inline long long Mnorm(long long x) { return (x % MOD + MOD) % MOD; }
const int MAXN = 1e6 + 6;
vector<long long> primesIn(long long s) {
  vector<long long> ret;
  for (long long i = 2; i * i <= s; i++) {
    if (s % i == 0) {
      ret.push_back(i);
      while (s % i == 0) s /= i;
    }
  }
  if (s != 1) ret.push_back(s);
  return ret;
}
int n, a[MAXN];
vector<int> tmp;
long long solve2() {
  int sz = tmp.size();
  long long rcnt = 0, lcnt = 0;
  long long rsum = 0, lsum = 0;
  for (int i = sz - 1; i > -1; i--) {
    rsum += rcnt;
    rcnt += tmp[i];
  }
  long long ans = rsum;
  for (int i = 0; i < sz; i++) {
    mnze(ans, rsum + lsum);
    lcnt += tmp[i];
    rcnt -= tmp[i];
    lsum += lcnt;
    rsum -= rcnt;
  }
  return ans;
}
void pback(int x) {
  if (tmp.size() == 0 && x == 0) return;
  tmp.push_back(x);
}
long long solve(long long p) {
  long long ans = 0;
  long long cur = 0;
  for (int i = 0; i < (int)n; i++) {
    if (cur + a[i] < p) {
      pback(a[i]);
      cur += a[i];
    } else {
      pback(p - cur);
      ans += solve2();
      tmp.clear();
      int b = a[i] - (p - cur);
      pback(b % p);
      cur = b % p;
    }
  }
  assert(tmp.size() == 0);
  return ans;
}
int main() {
  scan(n);
  for (int i = 0; i < (int)n; i++) scan(a[i]);
  long long S = 0;
  for (int i = 0; i < (int)n; i++) S += a[i];
  vector<long long> ps = primesIn(S);
  if (ps.size() == 0) {
    printf("-1\n");
    return 0;
  }
  long long ans = 0x3f3f3f3f3f3f3f3f;
  for (long long p : ps) {
    mnze(ans, solve(p));
  }
  printf("%lld\n", ans);
}
