#include <bits/stdc++.h>
using namespace std;
long long a[1000010];
int main() {
  int n;
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 1; i <= n; ++i) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  if (sum <= 1) {
    printf("-1\n");
    return 0;
  }
  long long ans = 9999999999999999;
  for (int i = 2; i * i <= sum; ++i) {
    if (sum % i) continue;
    long long cnt = 0, pre = 0;
    while (sum % i == 0) sum /= i;
    for (int j = 1; j <= n; ++j) {
      pre = (pre + a[j]) % i;
      cnt += min(pre, i - pre);
    }
    ans = min(ans, cnt);
  }
  if (sum > 1) {
    long long pre = 0, cnt = 0;
    for (int j = 1; j <= n; ++j) {
      pre = (pre + a[j]) % sum;
      cnt += min(pre, sum - pre);
    }
    ans = min(ans, cnt);
  }
  printf("%lld", ans);
}
