#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int MOD = 1e9 + 7;
int a[N];
long long int b[N];
vector<long long int> factors;
int n;
long long int solve(long long int div) {
  for (int i = 0; i < n; i++) {
    b[i] = a[i] % div;
  }
  long long int cur = 0;
  for (int i = 0; i < n; i++) {
    if (b[i] == 0) {
      continue;
    }
    if (b[i] * 2 <= div) {
      cur += b[i];
      b[i + 1] += b[i];
      b[i + 1] %= div;
    } else {
      for (int j = i + 1; j < n; j++) {
        if (b[j] == 0) {
          continue;
        }
        long long int req = min(b[j], div - b[i]);
        b[j] -= req;
        b[i] += req;
        cur += (j - i) * req;
        if (b[i] % div == 0) {
          if (b[j] == 0)
            i = j;
          else
            i = j - 1;
          break;
        }
      }
    }
  }
  return cur;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int sum = 0;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  if (sum == 1) return cout << -1, 0;
  for (long long int div = 2; div * div <= sum; div++) {
    if (sum % div == 0) {
      factors.push_back(div);
      while (sum % div == 0) {
        sum /= div;
      }
    }
  }
  if (sum > 1) factors.push_back(sum);
  long long int res = 2 * 1e18;
  for (auto i : factors) {
    long long int x = solve(i);
    res = min(res, x);
  }
  cout << res;
  return 0;
}
