#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
long long sum[maxn], arr[maxn];
int n;
long long get_cost(long long k) {
  long long ans = 0;
  for (int i = 0; i < n; ++i) {
    ans += min(sum[i] % k, k - sum[i] % k);
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> arr[i];
    if (!i)
      sum[i] = arr[i];
    else
      sum[i] = sum[i - 1] + arr[i];
  }
  long long p = 2, tmp = sum[n - 1];
  long long ans = 2e18;
  while (p * p <= tmp) {
    if (!(tmp % p)) {
      ans = min(ans, get_cost(p));
      while (tmp % p == 0) tmp /= p;
    }
    ++p;
  }
  if (tmp > 1) ans = min(ans, get_cost(tmp));
  cout << (ans == 2e18 ? -1 : ans) << endl;
  return 0;
}
