#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e6 + 10;
const long long INF = 1e9;
const long long linf = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
long long mod = 1e9 + 7;
long long n, a[maxn];
long long cal(long long x) {
  long long res = 0, now = 0;
  for (long long i = 1; i <= n; i++) {
    now += a[i];
    now %= x;
    res += min(now, x - now);
  }
  return res;
}
int32_t main() {
  std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  long long sum = 0;
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  long long ans = linf;
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i) continue;
    ans = min(ans, cal(i));
    while (sum % i == 0) sum /= i;
  }
  if (sum > 1) ans = min(ans, cal(sum));
  if (ans > linf - 1) ans = -1;
  cout << ans << endl;
  return 0;
}
