#include <bits/stdc++.h>
using namespace std;
long long N = 1e6 + 1;
long long n;
long long oo = 1e18;
vector<long long> prefix_sum(N);
vector<long long> prime;
void get_prime(long long sum) {
  vector<char> chk(N);
  for (long long i = 2; i < N; ++i) {
    if (!chk[i]) {
      if (sum % i == 0) prime.push_back(i);
      while (sum % i == 0) sum /= i;
      long long j = i + i;
      while (j < N) {
        chk[j] = 1;
        j += i;
      }
    }
  }
  if (sum > 1) prime.push_back(sum);
}
long long cal_res(long long d) {
  long long res = 0;
  for (long long i = 1; i <= n; ++i)
    res += min(prefix_sum[i] % d, d - prefix_sum[i] % d);
  return res;
}
void solve() {
  cin >> n;
  for (long long i = 1; i <= n; ++i) {
    cin >> prefix_sum[i];
    prefix_sum[i] += prefix_sum[i - 1];
  }
  get_prime(prefix_sum[n]);
  long long res = oo;
  for (auto& i : prime) res = min(res, cal_res(i));
  cout << (res == oo ? -1 : res) << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  solve();
  return 0;
}
