#include <bits/stdc++.h>
using namespace std;
long long sum, v[1000005], ans = 1e18, k, x;
vector<long long> primes;
int main() {
  int n;
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++)
    scanf("%lld", &v[i]), sum += v[i], v[i] += v[i - 1];
  if (sum == 1) {
    cout << -1;
    return 0;
  }
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i) continue;
    x = 0;
    k = i;
    for (int p = 1; p <= n; p++) x += min(v[p] % k, k - v[p] % k);
    ans = min(x, ans);
    while (sum && sum % i == 0) sum /= i;
  }
  if (sum > 1) {
    k = sum;
    x = 0;
    for (int p = 1; p <= n; p++) x += min(v[p] % k, k - v[p] % k);
    ans = min(x, ans);
  }
  cout << ans;
  return 0;
}
