#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
int read() {
  int x = 0, flag = 1;
  char c = getchar();
  while ((c > '9' || c < '0') && c != '-') c = getchar();
  if (c == '-') flag = 0, c = getchar();
  while (c <= '9' && c >= '0') {
    x = (x << 3) + (x << 1) + c - '0';
    c = getchar();
  }
  return flag ? x : -x;
}
const int maxn = 1e6 + 5;
int n;
long long s[maxn], ans = 1ll << 60;
long long solve(long long k) {
  long long ret = 0;
  for (int i = (1); i <= (int)(n - 1); i++) ret += min(s[i] % k, k - s[i] % k);
  return ret;
}
bool is_prime(long long k) {
  for (long long i = 2; i * i <= k; i++)
    if (k % i == 0) return 0;
  return 1;
}
int main() {
  n = read();
  for (int i = (1); i <= (int)(n); i++) s[i] = s[i - 1] + read();
  if (s[n] < 2) return puts("-1"), 0;
  if (is_prime(s[n]))
    ans = min(ans, solve(s[n]));
  else {
    for (long long i = 2; i * i <= s[n]; i++)
      if (s[n] % i == 0) {
        if (is_prime(i)) ans = min(ans, solve(i));
        if (is_prime(s[n] / i)) ans = min(ans, solve(s[n] / i));
      }
  }
  cout << ans;
  return 0;
}
