#include <bits/stdc++.h>
using namespace std;
inline int read() {
  register int x(0), f(1);
  register char c(getchar());
  while (c > '9' || c < '0') f = c == '-' ? -1 : 1, c = getchar();
  while (c <= '9' && c >= '0') x = x * 10 + c - 48, c = getchar();
  return x * f;
}
const int N = 1e6 + 10;
int n, a[N];
long long s, ans = 1e18;
long long solve(long long k) {
  long long pre = 0, res = 0;
  for (int i = 1; i <= n; ++i) (pre += a[i]) %= k, res += min(pre, k - pre);
  return res;
}
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) a[i] = read(), s += a[i];
  if (s <= 1) {
    puts("-1");
    return 0;
  }
  for (long long k = 2; k * k <= s; ++k)
    if (s % k == 0) {
      while (s % k == 0) s /= k;
      ans = min(ans, solve(k));
    }
  if (s > 1) ans = min(ans, solve(s));
  cout << ans << '\n';
  return 0;
}
