#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int inf = 1e9;
int add(int x, int y) { return (1ll * x + 1ll * y) % mod; }
int del(int x, int y) { return ((1ll * x - 1ll * y) % mod + mod) % mod; }
int mul(int x, int y) { return (1ll * x * 1ll * y) % mod; }
const int N = 1e6 + 5;
int n;
long long a[N], pre[N];
long long sum = 0;
bool p[N];
vector<long long> primes, lmao;
int main() {
  cin.tie(0), ios_base::sync_with_stdio(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i], sum += a[i];
  if (sum == 1) {
    cout << "-1\n";
    exit(0);
  }
  for (int i = 2; i < N; i++) p[i] = 1;
  for (int i = 2; i < N; i++) {
    if (p[i]) {
      primes.push_back(i);
      for (int j = 2 * i; j < N; j += i) p[j] = 0;
    }
  }
  for (int i = 0; i < primes.size(); i++) {
    if (sum % primes[i] == 0) {
      lmao.push_back(primes[i]);
      while (sum % primes[i] == 0) sum /= primes[i];
    }
  }
  if (sum > 1) lmao.push_back(sum);
  long long hihixd = 1e18;
  for (int k = 0; k < lmao.size(); k++) {
    long long ans = 0, sum = 0;
    for (int i = 1; i <= n; i++) {
      pre[i] = a[i] % lmao[k];
      pre[i] += pre[i - 1];
    }
    int li = 1, ri = 1;
    for (int i = 0; i <= n, li <= n; i++) {
      long long l = i * lmao[k], r = (i + 1) * lmao[k], md = (l + r + 1) / 2;
      while (ri <= n && pre[ri] < r) ri++;
      for (int j = li; j <= min(ri, n); j++) {
        if (pre[j] < md) ans += pre[j] - l;
        if (pre[j - 1] >= md) ans += r - pre[j - 1];
      }
      li = ri;
    }
    hihixd = min(hihixd, ans);
  }
  cout << hihixd;
}
