#include <bits/stdc++.h>
using namespace std;
int N;
int bin[1200010];
int base[1200010];
bool not_prime[1200010 + 5];
int prime[1200010 + 5], primei = 0;
long long sum = 0;
long long work(long long x) {
  long long sum = 0;
  long long pre = 0;
  for (int i = 1; i <= N; i++) {
    long long q = bin[i] % x;
    pre = (pre + q) % x;
    sum += min(pre, x - pre);
  }
  return sum;
}
bool is_p(long long x) {
  if (x < 2) return 0;
  for (int i = 0; i < primei; i++) {
    if (x % prime[i] == 0) return 0;
  }
  return 1;
}
int main() {
  cin >> N;
  not_prime[1] = 1;
  for (int i = 2; i <= 1200010; i++) {
    if (!not_prime[i]) {
      prime[primei++] = i;
    }
    for (int j = 0; j < primei && prime[j] * i < 1200010; j++) {
      not_prime[prime[j] * i] = 1;
      if (i % prime[j] == 0) {
        break;
      }
    }
  }
  for (int i = 1; i <= N; i++) {
    scanf("%d", &bin[i]);
    sum += bin[i];
  }
  long long ans = (long long)1000000000 * 1000000000;
  for (int i = 0; i < primei; i++) {
    if (sum % prime[i] == 0) {
      ans = min(ans, work(prime[i]));
    }
  }
  if (is_p(sum)) ans = min(ans, work(sum));
  if (ans == (long long)1000000000 * 1000000000) ans = -1;
  cout << ans << endl;
  return 0;
}
