#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL);
  int n;
  cin >> n;
  long long a[n];
  long long s = 0, m = 1e18;
  for (long long& i : a) cin >> i, s += i;
  vector<long long> f;
  for (long long i = 2; i * i <= s; i++)
    if (s % i == 0) {
      f.push_back(i);
      while (s % i == 0) s /= i;
    }
  if (s != 1) f.push_back(s);
  if (!f.size()) {
    cout << "-1\n";
    return 0;
  }
  for (long long p : f) {
    long long b[n];
    for (int i = 0; i < n; i++) b[i] = a[i];
    long long c = 0;
    int l = 0, r = 0;
    while (l < n) {
      if (b[l] % p * 2 <= p)
        c += b[l] % p, b[l + 1] += b[l] % p, l++;
      else {
        if (r <= l) r = l + 1;
        long long d = min(b[r], p - b[l] % p);
        b[l] += d, b[r] -= d, c += d * (r - l);
        if (b[l] % p == 0) l++;
        if (b[r] == 0) r++;
      }
    }
    m = min(m, c);
  }
  cout << m << "\n";
}
