#include <bits/stdc++.h>
using namespace std;
long long cal(const vector<int> &aa, int n, long long minDiv) {
  vector<int> a = aa;
  for (int i = 1; i <= n; i++) {
    a[i] %= minDiv;
  }
  long long ans = 0;
  long long curSum = 0;
  vector<long long> test;
  for (int i = 1, j = 0; i <= n; i = j) {
    int midIdx = 0;
    j = i - 1;
    curSum = 0;
    while (curSum < minDiv && j < n) {
      j++;
      assert(j <= n);
      long long leftNum = curSum;
      curSum += a[j];
      long long rightNum = max(0LL, minDiv - curSum);
      long long sub = max(0LL, curSum - minDiv);
      if (abs(rightNum - leftNum) <= a[j] - sub) {
        midIdx = j;
      }
    }
    if (curSum == 0) {
      break;
    }
    long long res = 0;
    for (int k = midIdx - 1; k >= i; k--) {
      res += (long long)(midIdx - k) * a[k];
    }
    for (int k = midIdx + 1; k <= j; k++) {
      int curNum = a[k];
      if (k == j) {
        curNum -= curSum - minDiv;
      }
      res += (long long)(k - midIdx) * curNum;
    }
    ans += res;
    test.push_back(res);
    a[j] = curSum - minDiv;
  }
  return ans;
}
int main() {
  int n;
  scanf("%d", &n);
  vector<int> a(n + 1);
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    sum += a[i];
  }
  if (sum <= 1LL) {
    do {
      printf("-1\n");
      return 0;
    } while (0);
    ;
  }
  vector<long long> div;
  long long tmp = sum;
  for (long long num = 2; num * num <= tmp; num++) {
    if (tmp % num == 0) {
      div.push_back(num);
      while (tmp % num == 0) {
        tmp /= num;
      }
    }
  }
  if (tmp != 1) {
    div.push_back(tmp);
  }
  long long ans = 1e18;
  for (auto e : div) {
    long long res = cal(a, n, e);
    ans = min(ans, res);
  }
  printf("%lld\n", ans);
  return 0;
}
