#include <bits/stdc++.h>
using namespace std;
long long n;
long long a[1000005];
long long solve(long long now) {
  long long res = 0, temp = 0;
  for (long long i = 1; i <= n; i++) {
    temp = (temp + a[i]) % now;
    res += min(temp, now - temp);
  }
  return res;
}
signed main() {
  long long sum = 0;
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]), sum += a[i];
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  long long ans = 1e18;
  for (long long i = 2; i * i <= sum; 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);
}
