#include <bits/stdc++.h>
using namespace std;
const int kMaxN = 1000007;
int64_t kInf = int64_t{1000000000000000007};
int64_t solve() {
  int n;
  cin >> n;
  static int a[kMaxN];
  int64_t sum = int64_t{0};
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
  };
  if (sum == int64_t{1}) return -1;
  vector<int64_t> primes;
  for (int64_t d = int64_t{2}; d * d <= sum; d++) {
    if (sum % d == int64_t{0}) primes.push_back(d);
    while (sum % d == int64_t{0}) sum /= d;
  }
  if (sum > int64_t{1}) primes.push_back(sum);
  ;
  int64_t best_answer = kInf;
  for (int64_t unit : primes) {
    ;
    int64_t answer = int64_t{0};
    int64_t median = (unit + 1) >> 1;
    static int b[kMaxN];
    int64_t b_sum = int64_t{0};
    for (int i = 0; i < n; i++) {
      b[i] = a[i] % unit;
      b_sum += b[i];
    };
    for (int num_units = b_sum / unit, cur = 0; num_units--;) {
      sum = b[cur];
      int median_pos;
      int last_pos;
      for (median_pos = cur; sum < median; median_pos++)
        sum += b[median_pos + 1];
      for (last_pos = median_pos; sum < unit; last_pos++)
        sum += b[last_pos + 1];
      for (int i = cur; i < last_pos; i++) {
        answer += int64_t{1} * b[i] * abs(i - median_pos);
      }
      answer += int64_t{1} * (b[last_pos] - (sum - unit)) *
                abs(last_pos - median_pos);
      ;
      ;
      b[last_pos] = (sum - unit);
      cur = last_pos;
    }
    best_answer = min(best_answer, answer);
    ;
  }
  return best_answer;
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  int test_cases_num = 1;
  for (int i = 1; i <= test_cases_num; i++) {
    if (false)
      if (test_cases_num > 1)
        if (false) cerr << "Test #" << i << ":\n";
    cout << solve() << "\n";
    if (false)
      if (test_cases_num > 1)
        if (false) cerr << "End of test #" << i << ".\n";
  }
  return 0;
}
