#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 100;
long long a[maxn];
long long getsum(int N, long long M) {
  long long ans = 0;
  long long pre = 0;
  for (int i = 1; i <= N; i++) {
    pre += a[i];
    pre %= M;
    ans += min(pre, M - pre);
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  int N;
  cin >> N;
  long long sum = 0;
  for (int i = 1; i <= N; i++) cin >> a[i], sum += a[i];
  if (sum <= 1) {
    cout << -1 << endl;
    return 0;
  }
  long long ans = 1ll << 62;
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i != 0) continue;
    while (sum % i == 0) sum /= i;
    ans = min(ans, getsum(N, i));
  }
  if (sum != 1) ans = min(ans, getsum(N, sum));
  cout << ans << endl;
  return 0;
}
