#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1e18, M = 1e9 + 7;
const long long int N = 1;
void solve() {
  long long int n;
  cin >> n;
  vector<long long int> v(n);
  for (long long int i = 0; i < n; ++i) cin >> v[i];
  long long int cnt = accumulate(v.begin(), v.end(), 0ll);
  if (cnt == 1) {
    cout << -1;
    return;
  }
  vector<long long int> st;
  for (long long int i = 2; i * i <= cnt; ++i) {
    if (cnt % i == 0) {
      st.push_back(i);
      while (cnt % i == 0) cnt /= i;
    }
  }
  if (cnt > 1) st.push_back(cnt);
  vector<pair<long long int, long long int> > tmp;
  long long int ans = inf;
  for (auto x : st) {
    tmp.clear();
    long long int y, take, sum = 0, z = 0;
    for (long long int i = 0; i < n; ++i) {
      y = v[i];
      take = min(y, x - sum);
      if (take) tmp.push_back({i, take});
      sum += take;
      if (sum == x) {
        long long int cur = 0, pos = 0;
        for (auto c : tmp) {
          cur += c.second;
          if (cur >= (x + 1) / 2) {
            pos = c.first;
            break;
          }
        }
        for (auto c : tmp) z += (abs(c.first - pos) * c.second);
        tmp.clear();
        sum = 0ll;
      }
      if (y > take) {
        tmp.push_back({i, (y - take) % x});
        sum += (y - take) % x;
      }
    }
    ans = min(ans, z);
  }
  cout << ans;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long int t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
