#include <bits/stdc++.h>
using namespace std;
const long long N = 3e6 + 7;
const long long inf = 1e18;
long long t, n;
long long a[N], b[N], c[N];
long long p1[N], p2[N], s1[N], s2[N];
long long gao(long long tot) {
  s1[tot + 1] = s2[tot + 1] = 0;
  for (long long i = tot; i >= 1; i--) {
    s1[i] = s1[i + 1] + c[i];
    s2[i] = s2[i + 1] + s1[i];
  }
  long long res = s2[1];
  for (long long i = 1; i <= tot; i++) {
    p1[i] = p1[i - 1] + c[i];
    p2[i] = p2[i - 1] + p1[i];
    res = min(res, p2[i - 1] + s2[i + 1]);
  }
  return res;
}
long long solve(long long k) {
  long long res = 0;
  long long tot = 0, num = 0;
  for (long long i = 1; i <= n; i++) {
    long long tmp = a[i] % k;
    num += tmp;
    c[++tot] = tmp;
    if (num > k) {
      c[tot] -= num - k;
      res += gao(tot);
      tot = 1;
      c[tot] = num - k;
      num = num - k;
    } else if (num == k) {
      res += gao(tot);
      num = 0;
      tot = 0;
    }
  }
  return res;
}
int main() {
  scanf("%lld", &n);
  long long sum = 0;
  for (long long i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  long long ans = inf, tmp = sum;
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  if (sum == 0) {
    printf("0\n");
    return 0;
  }
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i) continue;
    while (sum % i == 0) sum /= i;
    ans = min(ans, solve(i));
  }
  if (sum > 1) ans = min(ans, solve(sum));
  printf("%lld\n", ans);
}
