#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int f = 1, x = 0;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
inline long long readll() {
  long long f = 1, x = 0;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
const int MAXN = 1e6 + 5;
int n;
long long sum, s[MAXN];
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) sum += (s[i] = read()), s[i] += s[i - 1];
  vector<long long> vec;
  for (long long i = 2; i * i <= sum; ++i) {
    if (sum % i == 0) {
      vec.push_back(i);
      while (sum % i == 0) sum /= i;
    }
  }
  if (sum != 1) vec.push_back(sum);
  long long ans = 1e18;
  for (int t = 0; t < (int)vec.size(); ++t) {
    long long k = vec[t], ta = 0;
    for (int i = 1; i <= n; ++i) ta += min(s[i] % k, k - s[i] % k);
    ans = min(ans, ta);
  }
  cout << ((ans == 1e18) ? -1 : ans) << endl;
  return 0;
}
