#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18 + 7;
const long long N = 1E6 + 7;
long long arr[N];
long long n;
long long cal(long long x) {
  long long sum = 0, s = 0;
  for (long long i = 1; i <= n; i++) {
    s = (s + arr[i]) % x;
    sum += min(s, x - s);
  }
  return sum;
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n;
  long long cnt = 0;
  for (long long i = 1; i <= n; i++) {
    cin >> arr[i];
    cnt += arr[i];
  }
  if (cnt == 1) {
    cout << -1 << endl;
    return 0;
  }
  if (n == 1) {
    cout << 0 << endl;
    return 0;
  }
  long long m = sqrt(cnt);
  long long sum = INF;
  for (long long i = 2; i <= m; i++) {
    if (cnt % i == 0) {
      sum = min(sum, cal(i));
      while (cnt % i == 0) cnt /= i;
    }
  }
  if (cnt != 1) sum = min(sum, cal(cnt));
  cout << sum << endl;
  return 0;
}
