#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 50;
long long n, a[N], sum, ans = LLONG_MAX;
long long deal(long long x) {
  long long ans = 0, now = 0;
  for (int i = 1; i <= n; i++) {
    long long k = (now + a[i] + x) % x;
    ans += min(k, x - k);
    now = (k < x - k) ? k : k - x;
  }
  return ans;
}
int main() {
  scanf("%I64d", &n);
  for (int i = 1; i <= n; i++) scanf("%I64d", a + i), sum += a[i];
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i == 0) {
      ans = min(ans, deal(i));
      while (sum % i == 0) sum /= i;
    }
  }
  if (sum > 1) ans = min(ans, deal(sum));
  if (ans == LLONG_MAX) ans = -1;
  printf("%I64d", ans);
}
