#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int inf = 1e9 + 10;
const long long INF = 1e18 + 10;
vector<long long> pref(N), suff(N);
vector<pair<int, int> > b;
void solve(int n, vector<int> a, long long sum, long long &ans) {
  for (auto &x : a) {
    x %= sum;
  }
  int r = 0;
  long long cur_ans = 0;
  while (r < n) {
    long long now = 0;
    while (r < n && now + a[r] <= sum) {
      now += a[r];
      b.push_back({r, a[r]});
      r++;
    }
    if (r < n && now < sum) {
      int dist = sum - now;
      a[r] -= dist;
      b.push_back({r, dist});
    }
    int m = b.size();
    long long sum_a = 0, res = 0;
    int last = b[0].first;
    for (int i = 0; i < m; i++) {
      int delta = b[i].first - last;
      res += sum_a * delta;
      pref[i] = res;
      sum_a += b[i].second;
      last = b[i].first;
    }
    sum_a = 0, res = 0;
    last = b.back().first;
    for (int i = m - 1; i > -1; i--) {
      int delta = last - b.back().first;
      res += sum_a * delta;
      suff[i] = res;
      sum_a += b.back().second;
      last = b.back().first;
      b.pop_back();
    }
    long long mn = INF;
    for (int i = 0; i < m; i++) {
      mn = min(mn, pref[i] + suff[i]);
    }
    cur_ans += mn;
  }
  ans = min(ans, cur_ans);
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  int n;
  cin >> n;
  long long sum = 0;
  vector<int> a(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  vector<long long> col;
  long long x = sum;
  for (int i = 2; 1LL * i * i <= x; i++) {
    if (x % i == 0) {
      col.push_back(i);
      while (x % i == 0) {
        x /= i;
      }
    }
  }
  if (x != 1) {
    col.push_back(x);
  }
  long long ans = INF;
  for (auto x : col) {
    solve(n, a, x, ans);
  }
  if (ans == INF) {
    ans = -1;
  }
  cout << ans << "\n";
  return 0;
}
