#include <bits/stdc++.h>
using namespace std;
int n;
long long a[1000010];
long long A[1000010];
long long a1[1000010];
long long a2[1000010];
long long s;
vector<long long> vec;
void init() {
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) {
    scanf("%lld", A + i);
    s += A[i];
  }
}
long long ans = 1ll << 60;
long long cal(long long val) {
  long long cur = 0, l = 0, re = 0;
  long long res = 0;
  for (int i = 0; i < n; ++i) {
    if (i != 0) a1[i] = a1[i - 1] + cur;
    a[i] = A[i];
    if (cur + a[i] > val)
      a[i] = val - cur, re = A[i] - a[i];
    else
      re = 0;
    cur += a[i];
    if (cur == val) {
      a2[i] = 0;
      cur = 0;
      long long tmp = 1ll << 60;
      for (int j = i; j >= l; --j) {
        if (j != i) a2[j] = a2[j + 1] + cur;
        cur += a[j];
        if (tmp > a1[j] + a2[j])
          tmp = a1[j] + a2[j];
        else
          break;
      }
      res += tmp;
      if (res >= ans) return ans + 1;
      l = i;
      a[i] = cur = re % val;
      a1[i] = 0;
    }
  }
  return res;
}
void sol() {
  if (s == 1) return puts("-1"), void();
  for (long long i = 2; i * i <= s; ++i)
    if (s % i == 0) {
      vec.push_back(i);
      vec.push_back(s / i);
    }
  vec.push_back(s);
  sort(vec.begin(), vec.end());
  for (long long i : vec) {
    long long t = cal(i);
    ans = min(ans, t);
  }
  cout << ans << endl;
}
int main() {
  int T = 1;
  while (T--) {
    init();
    sol();
  }
}
