#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
long long a[maxn], b[maxn];
int n;
long long ans;
inline long long read() {
  long long ans = 0;
  char ch = getchar();
  while (ch < '0' || ch > '9') ch = getchar();
  while (ch >= '0' && ch <= '9') {
    ans = ans * 10 + ch - '0';
    ch = getchar();
  }
  return ans;
}
long long solve(long long mod) {
  long long sol = 0;
  int i;
  for (i = 0; i < n; i++) b[i] = a[i] % mod;
  for (i = 0; i < n; i++) {
    sol += min(b[i], mod - b[i]);
    if (sol > ans) break;
    b[i + 1] = (b[i + 1] + b[i]) % mod;
  }
  return sol;
}
int main() {
  int i;
  long long tot;
  n = read();
  tot = 0;
  for (i = 0; i < n; i++) tot += (a[i] = read());
  if (tot == 1) {
    puts("-1");
    return 0;
  }
  ans = 1e18;
  for (i = 2; 1LL * i * i <= tot; i++)
    if (tot % i == 0) {
      ans = min(ans, solve(i));
      while (tot % i == 0) tot /= i;
    }
  if (tot > 1) ans = min(ans, solve(tot));
  printf("%lld\n", ans);
  return 0;
}
