#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const double eps = 1e-9;
const int maxn = 3e5 + 5;
const long long INF = 0x3f3f3f3f3f3f3f3fll;
const int inf = 0x3f3f3f3f;
inline int read() {
  int ret = 0, sgn = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') sgn = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    ret = ret * 10 + ch - '0';
    ch = getchar();
  }
  return ret * sgn;
}
inline void Out(int a) {
  if (a > 9) Out(a / 10);
  putchar(a % 10 + '0');
}
int qpow(int m, int k, int mod) {
  int res = 1, t = m;
  while (k) {
    if (k & 1) res = res * t % mod;
    t = t * t % mod;
    k >>= 1;
  }
  return res;
}
long long __gcd(long long a, long long b) {
  return b == 0 ? a : __gcd(b, a % b);
}
long long lcm(long long a, long long b) { return a * b / __gcd(a, b); }
long long a[2001000], n, sum, minans = INF;
long long solve(long long res) {
  long long ans = 0, temp = 0;
  for (long long i = 1; i <= n; i++) {
    temp = (temp + a[i]) % res;
    ans += min(temp, res - temp);
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  sum = 0;
  for (long long i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    sum += a[i];
  }
  if (sum == 1) {
    cout << "-1" << endl;
    return 0;
  }
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i) continue;
    minans = min(minans, solve(i));
    while (sum % i == 0) sum /= i;
  }
  if (sum > 1) minans = min(minans, solve(sum));
  cout << minans << endl;
  return 0;
}
