#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000010;
int a[maxn];
long long sum[maxn];
int n;
inline long long solve(long long k) {
  long long res = 0;
  for (int i = 1; i <= n; i++) {
    long long x = sum[i] % k;
    res += min(x, k - x);
  }
  return res;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", a + i);
    sum[i] = a[i] + sum[i - 1];
  }
  long long tot = sum[n], ans = 0x7f7f7f7f7f7f7f7f;
  for (long long i = 2; i * i <= tot; i++) {
    if (tot % i) continue;
    ans = min(ans, solve(i));
    while (tot % i == 0) {
      tot /= i;
    }
  }
  if (tot != 1) ans = min(ans, solve(tot));
  if (ans != 0x7f7f7f7f7f7f7f7f)
    cout << ans << endl;
  else
    cout << -1 << endl;
  return 0;
}
