#include <bits/stdc++.h>
#pragma optimization_level 3
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e6 + 9;
long long a[maxn], n, b[maxn];
long long cal(long long val) {
  for (int i = int(1); i <= int(n); ++i) b[i] = a[i] % val;
  long long ans(0);
  for (int i = int(1); i <= int(n); ++i) {
    if (b[i] < val - b[i]) {
      b[i + 1] += b[i], ans += b[i];
      if (b[i + 1] >= val) b[i + 1] -= val;
    } else {
      b[i + 1] -= val - b[i];
      if (b[i + 1] < 0) b[i + 1] += val;
      ans += val - b[i];
    }
  }
  return ans;
}
int pri[maxn];
void init() {
  for (int i = 2; i < maxn; ++i) {
    if (!pri[i]) pri[++pri[0]] = i;
    for (int j = 1; j <= pri[0] && pri[j] < maxn / i; ++j) {
      pri[pri[j] * i] = 1;
      if (i % pri[j] == 0) break;
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  init();
  cin >> n;
  for (int i = int(1); i <= int(n); ++i) cin >> a[i];
  long long sum = accumulate(a + 1, a + 1 + n, 0ll);
  long long ans = 1ll * inf * inf;
  for (int i = int(1); i <= int(pri[0]); ++i) {
    if (sum % pri[i] == 0) {
      while (sum % pri[i] == 0) sum /= pri[i];
      ans = min(ans, cal(pri[i]));
    }
  }
  if (sum != 1) ans = min(ans, cal(sum));
  if (ans == 1ll * inf * inf) ans = -1;
  cout << ans << endl;
}
