#include <bits/stdc++.h>
using namespace std;
const long long DESPACITO = 1000000000000000000;
auto Try = [](const vector<long long>& a, long long k) {
  long long res = 0;
  for (long long i = 0; i < (long long)(a).size() - 1; i++)
    res += min(a[i] % k, k - (a[i] % k));
  return res;
};
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long i, n, sum = 0, ans = DESPACITO;
  cin >> n;
  vector<long long> a(n);
  for (auto& x : a) cin >> x;
  for (i = 1; i < n; i++) a[i] += a[i - 1];
  sum = a.back();
  for (i = 2; i * i <= sum and sum > 1; i++) {
    if (sum % i) continue;
    ans = min(ans, Try(a, i));
    while (sum % i == 0) sum /= i;
  }
  if (sum > 1) ans = min(ans, Try(a, sum));
  cout << (ans == DESPACITO ? -1 : ans);
  return 0;
}
