#include <bits/stdc++.h>
using namespace std;
long long solve(long long d, vector<long long> a) {
  int lo = 0;
  long long cur_sum = 0;
  long long sol = 0;
  for (int i = 0; i < (int)a.size(); i++) {
    a[i] %= d;
    cur_sum += a[i];
    if (cur_sum >= d) {
      long long tmp = cur_sum - d;
      a[i] -= tmp;
      long long sum_l = 0, moves_l = 0, sum_r = 0, moves_r = 0;
      long long best = 1e18;
      for (int j = i; j >= lo; j--) {
        sum_r += a[j];
        moves_r += sum_r;
      }
      for (int j = lo; j <= i; j++) {
        moves_r -= sum_r;
        sum_r -= a[j];
        best = min(best, moves_l + moves_r);
        sum_l += a[j];
        moves_l += sum_l;
      }
      sol += best;
      lo = i;
      a[i] = tmp;
      cur_sum = tmp;
    }
  }
  return sol;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  vector<long long> a(n);
  long long sum = 0;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  if (sum == 1) {
    cout << -1;
    return 0;
  }
  vector<long long> d;
  for (long long i = 2; (long long)i * i <= sum; i++) {
    if (sum % i != 0) continue;
    d.push_back(i);
    while (sum % i == 0) sum /= i;
  }
  if (sum != 1) d.push_back(sum);
  long long sol = 1e18;
  for (long long i : d) sol = min(sol, solve(i, a));
  cout << sol;
  return 0;
}
