#include <bits/stdc++.h>
using namespace std;
int n;
int a[1000005];
long long solve(long long x) {
  long long ans = 0, sum = 0;
  for (int i = 1; i <= n; i++) {
    ans += min(sum % x, x - sum % x);
    sum += a[i];
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]), sum += a[i];
  if (sum == 1)
    printf("-1\n");
  else {
    long long ans = 1e18;
    long long tmp = sum;
    for (long long i = 2; i * i <= tmp; i++) {
      if (sum % i == 0) ans = min(ans, solve(i));
      while (sum % i == 0) sum /= i;
    }
    if (sum != 1) ans = min(ans, solve(sum));
    printf("%lld\n", ans);
  }
}
