#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> ara, x;
long long s, ans = 1e18;
int main() {
  iostream::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> k;
    ara.push_back(k);
    s += k;
  }
  if (s < 2) {
    cout << "-1";
    exit(0);
  }
  for (long long i = 2; i <= sqrtl(s); i++) {
    if (s % i == 0) {
      x.push_back(i);
      while (s % i == 0) s /= i;
    }
  }
  if (s > 1) x.push_back(s);
  for (long long a : x) {
    vector<int> t = ara;
    for (int i = 0; i < n; i++) t[i] %= a;
    s = 0;
    for (int i = 0; i < n; i++) {
      if (t[i] > 0) {
        int j = i, sum = 0;
        vector<int> z;
        while (j < n && sum < a) {
          sum += t[j];
          if (t[j] > 0) z.push_back(j);
          j++;
        }
        int l = z[0], r = z.back();
        long long s1, s2;
        while (l < r - 2) {
          int a = (2 * l + r) / 3, b = (l + 2 * r) / 3;
          s1 = 0;
          s2 = 0;
          for (int p : z) {
            s1 += abs(p - a);
            s2 += abs(p - b);
          }
          if (s1 <= s2)
            r = b;
          else
            l = a;
        }
        int p1 = (l + r) / 2;
        for (int p : z) s += abs(p - p1);
        i = j - 1;
      }
    }
    ans = min(ans, s);
  }
  cout << ans;
  return 0;
}
