#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2")
using namespace std;
long long minimize(const vector<pair<long long, long long> > &pos) {
  long long sum_nr = 0;
  for (auto pr : pos) sum_nr += pr.second;
  sum_nr /= 2;
  long long loc = -1;
  for (auto pr : pos) {
    sum_nr -= pr.second;
    if (sum_nr < 0) {
      loc = pr.first;
      break;
    }
  }
  long long ret = 0;
  for (auto pr : pos) ret += abs(pr.first - loc) * pr.second;
  return ret;
}
long long Try(const vector<int> &A, long long p) {
  int n = ((int)(A).size());
  long long sum = 0;
  vector<pair<long long, long long> > cur_nr = {};
  long long cursum = 0;
  for (auto i = (0); i != (n); ++i) {
    if (A[i] == 0) continue;
    long long rem = p - (cursum);
    if (A[i] <= rem) {
      cursum += A[i];
      cur_nr.emplace_back(i, A[i]);
      if (p == cursum) {
        sum += minimize(cur_nr);
        cur_nr.clear();
        cursum = 0;
      }
    } else {
      cursum += rem;
      cur_nr.emplace_back(i, rem);
      long long A_left = (A[i] - rem) % p;
      sum += minimize(cur_nr);
      cur_nr.clear();
      cursum = A_left;
      cur_nr.emplace_back(i, A_left);
    }
  }
  return sum;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n;
  cin >> n;
  vector<int> A(n);
  for (auto i = (0); i != (n); ++i) cin >> A[i];
  long long sum = 0;
  for (auto i = (0); i != (n); ++i) sum += A[i];
  vector<long long> pr_divs;
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i != 0) continue;
    while (sum % i == 0) sum /= i;
    pr_divs.push_back(i);
  }
  if (sum > 1) pr_divs.push_back(sum);
  long long answer = LLONG_MAX;
  for (long long p : pr_divs) {
    answer = min(answer, Try(A, p));
  }
  if (answer == LLONG_MAX) answer = -1;
  cout << answer << endl;
  return 0;
}
