#include <bits/stdc++.h>
using namespace std;
mt19937 rng(std::chrono::system_clock::now().time_since_epoch().count());
const int N = 1e6;
long long ans = 1e18;
int n, a[N], sum;
long long b[N + 1];
long long find(long long cur) {
  long long ret = 0;
  for (int i = 0; i < n; i++) b[i] = a[i] % cur;
  long long cost = 0, need = 0;
  for (int l = 0; l < n; l++) {
    ret += need;
    int mn = min(b[l], need);
    need -= mn;
    b[l] -= mn;
    if (b[l]) {
      if (b[l] <= cur - b[l]) {
        ret += b[l];
        b[l + 1] = (b[l] + b[l + 1]) % cur;
      } else
        need = cur - b[l];
    }
  }
  return ret;
}
int main() {
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", a + i);
    sum += a[i];
  }
  for (int i = 2; i * 1LL * i <= sum; i++) {
    if (sum % i == 0) {
      ans = min(ans, find(i));
      while (sum % i == 0) sum /= i;
    }
  }
  if (sum != 1) ans = min(ans, find(sum));
  if (ans == 1e18) ans = -1;
  printf("%lld\n", ans);
}
