#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long int llINF = INT64_MAX;
const int N = 1123456;
const int MAX_SIEVE = 1123456;
int n;
long long int a[N], sum = 0;
vector<int> prim;
int mark[MAX_SIEVE];
void crivo() {
  for (int i = 2; i < MAX_SIEVE; i++) {
    if (!mark[i]) prim.push_back(i);
    for (int p : prim) {
      if (i * p >= MAX_SIEVE) break;
      mark[i * p] = 1;
      if (i % p == 0) break;
    }
  }
}
long long int solve(long long int sm, long long int k) {
  long long int prosum = 0;
  long long int ans = 0;
  for (int i = 0; i < n - 1; i++) {
    prosum += a[i];
    ans += min(k - prosum % k, prosum % k);
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  crivo();
  long long int scpoy = sum, ans = llINF;
  for (auto x : prim) {
    if (sum % x == 0) {
      while (sum % x == 0) sum /= x;
      ans = min(ans, solve(scpoy, x));
    }
  }
  if (sum != 1) ans = min(ans, solve(scpoy, scpoy));
  printf("%lld\n", ans);
}
