#include <bits/stdc++.h>
using namespace std;
const int N = int(1e6 + 10);
long long a[N];
int n;
long long solve(long long d) {
  long long ac = 0LL;
  long long ret = 0LL;
  long long cost = 0LL;
  long long carry = 0;
  for (int i = 0; i < n; i++) {
    cost += min(carry, d - carry);
    if (a[i]) {
      carry = (carry + a[i]) % d;
    }
  }
  return cost;
}
int main() {
  scanf("%d", &n);
  long long sum = 0LL;
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  if (sum == 1LL) {
    printf("-1\n");
    return 0;
  }
  long long best = -1;
  for (long long d = 2LL; d * d <= sum; d++) {
    if (sum % d == 0LL) {
      if (best == -1) {
        best = solve(d);
      } else {
        best = min(best, solve(d));
      }
      while (sum % d == 0LL) {
        sum /= d;
      }
    }
  }
  if (sum != 1LL) {
    if (best == -1) {
      best = solve(sum);
    } else {
      best = min(best, solve(sum));
    }
  }
  printf("%lld\n", best);
  return 0;
}
