#include <bits/stdc++.h>
using namespace std;
long long gcd(long long x, long long y) { return (!y ? x : gcd(y, x % y)); }
const long long maxn = 1e6 + 10;
long long mark[maxn];
void prep() {
  for (long long i = 2; i < maxn; i++) {
    if (mark[i]) continue;
    for (long long j = 2 * i; j < maxn; j += i) mark[j] = 1;
  }
}
const long long inf = 1e18;
long long a[maxn], b[maxn];
long long get(long long n, long long mod) {
  if (mod <= 1) return inf;
  for (long long i = 0; i < n; i++) b[i] = a[i] % mod;
  vector<pair<long long, long long> > lst;
  long long ted = 0, md = -1, ans = 0;
  for (long long i = 0; i < n; i++) {
    ted += b[i];
    if (ted >= (mod + 1) / 2 && md == -1) {
      md = i;
    }
    if (ted >= mod) {
      lst.push_back({i, mod - ted + b[i]});
      for (auto x : lst) {
        ans += abs(x.first - md) * x.second;
      }
      lst.clear();
      ted -= mod;
      md = -1;
      if (ted > mod) lst.push_back({i, ted - mod});
    } else {
      lst.push_back({i, b[i]});
    }
  }
  return ans;
}
int32_t main() {
  ios::sync_with_stdio(0), cin.tie(0);
  long long n;
  cin >> n;
  long long sum = 0;
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  long long cur = sum;
  long long ans = inf;
  for (long long i = 2; i < maxn; i++) {
    if (mark[i] || sum % i != 0) continue;
    while (cur % i == 0) cur /= i;
    ans = min(ans, get(n, i));
  }
  ans = min(ans, get(n, cur));
  cout << (ans >= inf ? -1 : ans) << '\n';
}
