#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7, Base = 998244353;
const long long N = 1e6 + 7;
const long long INF = 1LL * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 + 7LL;
const double pie = acos(-1.0);
const double EPS = 1e-9;
long long n, s[N], a[N], x, ans = INF;
long long op(long long k) {
  long long x = 0;
  for (long long i = 1; i <= n; ++i) x += min(s[i] % k, k - (s[i] % k));
  return x;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 1; i <= n; ++i) cin >> a[i], s[i] += a[i] + s[i - 1];
  x = s[n];
  if (s[n] == 1) {
    cout << -1 << '\n';
    return 0;
  }
  for (long long i = 2; i * i <= x; ++i) {
    if (x % i == 0) {
      ans = min(ans, op(i));
      while (x % i == 0) x /= i;
    }
  }
  if (x > 1) ans = min(ans, op(x));
  cout << ans << '\n';
  return 0;
}
