#include <bits/stdc++.h>
using namespace std;
const int N = 1000000 + 10;
int a[N];
int main() {
  int n;
  scanf("%d", &n);
  long long s = 0;
  for (int i = 0; i < n; i++) scanf("%d", &a[i]), s += a[i];
  if (s == 1) return 0 * printf("%d\n", -1);
  vector<long long> p;
  for (long long i = 2; i * i <= s; i++) {
    if (s % i == 0) p.push_back(i);
    while (s % i == 0) s /= i;
  }
  if (s != 1) p.push_back(s);
  long long ans = 1e18;
  for (long long d : p) {
    long long tmp = 0;
    long long rem = 0;
    for (int i = 0; i < n; i++) {
      if (rem < d / 2 + 1) tmp += rem;
      rem += a[i];
      rem %= d;
    }
    rem = 0;
    for (int i = n - 1; i >= 0; i--) {
      if (rem < d / 2 + 1 - (d % 2 == 0)) tmp += rem;
      rem += a[i];
      rem %= d;
    }
    ans = min(ans, tmp);
  }
  cout << ans << endl;
}
