#include <bits/stdc++.h>
using namespace std;
template <typename Tp>
void read(Tp &num) {
  num = 0;
  Tp f = 1;
  char c = getchar();
  while (!isdigit(c)) c == '-' ? f = -1 : 1, c = getchar();
  while (isdigit(c)) num = num * 10 + (c ^ 48), c = getchar();
  num *= f;
}
template <typename Tp, typename... etc>
void read(Tp &num, etc &...more) {
  read(num);
  read(more...);
}
long long rans = 1E18, n, ans, sum, a[1000007], b[1000007];
inline void work(long long x) {
  ans = 0;
  for (register int i = 1; i <= n; ++i) b[i] = a[i] % x;
  for (register int i = 1; i <= n; ++i) {
    ans += min(b[i], x - b[i]);
    b[i + 1] = (b[i + 1] + b[i]) % x;
  }
  rans = min(ans, rans);
}
int main() {
  read(n);
  for (register int i = 1; i <= n; ++i) {
    read(a[i]);
    sum += a[i];
  }
  for (register long long i = 2; i * i <= sum; ++i) {
    if (sum % i == 0) work(i);
    while (sum % i == 0) sum /= i;
  }
  if (sum > 1) work(sum);
  if (rans == 1E18) return printf("-1\n"), 0;
  printf("%lld\n", rans);
}
