#include <bits/stdc++.h>
using namespace std;
int n;
int a[1001115];
long long s[1001115];
long long ans = 0x7f7f7f7f7f7f7f7f;
void chk(long long p) {
  long long ret = 0;
  for (int i = 1; i <= n; i++) {
    auto x = (s[i] % p);
    ret += min(x, p - x);
  }
  ans = min(ret, ans);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) s[i] = s[i - 1] + a[i];
  long long x = s[n];
  for (int i = 2; (long long)i * i <= x; i++) {
    if (x % i == 0) {
      while (x % i == 0) x /= i;
      chk(i);
    }
  }
  if (x > 1) chk(x);
  cout << (ans == 0x7f7f7f7f7f7f7f7f ? -1 : ans) << endl;
}
