#include <bits/stdc++.h>
using namespace std;
int a[1000005], n;
long long ans = 0;
long long now = 0;
long long solve(long long p) {
  ans = 0;
  now = 0;
  for (int i = 1; i <= n; i++) {
    now += a[i];
    now %= p;
    ans += min(now, p - now);
  }
  return ans;
}
int main() {
  cin >> n;
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d", a + i);
    sum = sum + a[i];
  }
  if (sum == 1) {
    cout << "-1" << endl;
  } else {
    long long ans0 = (1ll << 62);
    for (int p = 2; p <= 1e6; p++) {
      if (sum % p == 0) {
        ans0 = min(ans0, solve(p));
        while (sum % p == 0) sum /= p;
      }
    }
    if (sum != 1) ans0 = min(ans0, solve(sum));
    cout << ans0 << endl;
  }
  return 0;
}
