#include <bits/stdc++.h>
using namespace std;
long long inf = 1e18;
const int maxn = 1e6 + 5;
int a[maxn];
bool p[maxn];
void upd(long long &var, long long val) { var = min(var, val); }
int main() {
  int n;
  cin >> n;
  long long s = 0;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    s += a[i];
  }
  if (s == 1)
    cout << -1;
  else {
    vector<long long> d;
    for (long long i = 2; i * i <= s; i++) {
      if (!p[i]) {
        if (s % i == 0) {
          d.push_back(i);
          d.push_back(s / i);
        }
        for (long long j = i * 2; j * j <= s; j += i) {
          p[j] = true;
        }
      }
    }
    if (d.empty()) d.push_back(s);
    long long ans = inf;
    for (long long m : d) {
      long long sum = 0;
      long long a_cnt = 0, b_cnt = 0;
      long long a_cost = 0, b_cost = 0;
      for (long long x : a) {
        sum += x;
        long long cnt = sum / m;
        long long cand_a_cost = inf;
        long long d = x / m + 1;
        if (a_cnt == cnt + 1 - d)
          upd(cand_a_cost, a_cost + abs(sum - x - a_cnt * m));
        if (b_cnt == cnt + 1 - d)
          upd(cand_a_cost, b_cost + abs(sum - x - b_cnt * m));
        d = x / m;
        if (a_cnt == cnt + 1 - d)
          upd(cand_a_cost, a_cost + abs(sum - x - a_cnt * m));
        if (b_cnt == cnt + 1 - d)
          upd(cand_a_cost, b_cost + abs(sum - x - b_cnt * m));
        long long cand_b_cost = inf;
        d = x / m + 1;
        if (a_cnt == cnt - d)
          upd(cand_b_cost, a_cost + abs(sum - x - a_cnt * m));
        if (b_cnt == cnt - d)
          upd(cand_b_cost, b_cost + abs(sum - x - b_cnt * m));
        d = x / m;
        if (a_cnt == cnt - d)
          upd(cand_b_cost, a_cost + abs(sum - x - a_cnt * m));
        if (b_cnt == cnt - d)
          upd(cand_b_cost, b_cost + abs(sum - x - b_cnt * m));
        a_cnt = cnt + 1;
        b_cnt = cnt;
        a_cost = cand_a_cost;
        b_cost = cand_b_cost;
      }
      if (a_cnt * m == sum) upd(ans, a_cost);
      if (b_cnt * m == sum) upd(ans, b_cost);
    }
    cout << ans << endl;
  }
  return 0;
}
