#include <bits/stdc++.h>
using namespace std;
const long long N = 5000005, inf = 1e18;
long long mp[N], t[N], tot, tot1, a[N];
pair<long long, long long> s[N];
void init(long long n) {
  mp[1] = 1;
  for (long long i = 2; i <= n; i++) {
    if (!mp[i]) t[++tot] = i;
    for (long long j = 1; t[j] * i <= n && j <= tot; j++) {
      mp[t[j] * i] = 1;
      if (i % t[j] == 0) break;
    }
  }
}
void add(long long x, long long y) {
  tot1++;
  s[tot1] = make_pair(s[tot1 - 1].first + x, y);
}
long long work1() {
  long long ans = 0, now = 1;
  for (long long i = 1; i <= tot1; i++) {
    if (s[i].first > s[tot1].first / 2) {
      now = i;
      break;
    }
  }
  for (long long i = 1; i <= tot1; i++)
    ans += abs(s[now].second - s[i].second) * (s[i].first - s[i - 1].first);
  tot1 = 0;
  return ans;
}
long long work(long long k, long long n) {
  long long ans = 0;
  for (long long i = 1; i <= n; i++) {
    long long x = a[i] % k;
    long long now = s[tot1].first;
    if (now + x >= k)
      add(k - now, i), ans += work1(), add(x + now - k, i);
    else if (x)
      add(x, i);
  }
  return ans;
}
signed main() {
  long long n, ans = inf, sum = 0;
  scanf("%lld", &n);
  init(2e6);
  for (long long i = 1; i <= n; i++) {
    scanf("%lld", a + i);
    sum += a[i];
  }
  for (long long i = 1; t[i] * t[i] <= sum; i++) {
    if (sum % t[i] == 0) ans = min(ans, work(t[i], n));
    while (sum % t[i] == 0) sum /= t[i];
  }
  if (sum > 1) ans = min(ans, work(sum, n));
  printf("%lld\n", ans == inf ? -1 : ans);
  return 0;
}
