#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
const long long mod = 998244353;
const long long INF = (1e18);
long long a[((1000000) + 5)];
long long ans;
int n;
void solve(long long d) {
  long long pre = 0, cnt = 0;
  for (int i = 1; i <= n; i++) {
    long long x = (a[i] + pre) % d;
    long long ad = min(x, d - x);
    cnt += ad;
    pre = x;
  }
  ans = min(ans, cnt);
}
int main() {
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  ans = INF;
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i == 0) {
      solve(i);
      while (sum % i == 0) sum /= i;
    }
  }
  if (sum > 1) solve(sum);
  if (ans == INF) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
