#include <bits/stdc++.h>
void pt() { std::cout << '\n'; }
template <typename T, typename... Args>
void pt(T a, Args... args) {
  std::cout << a << ' ';
  pt(args...);
}
using namespace std;
const int N = 1e6 + 5;
int n;
int a[N];
long long gao(long long d) {
  long long res = 0, pre = 0;
  for (int i = 1; i <= n; i++) {
    pre = (pre + a[i]) % d;
    res += min(pre, d - pre);
  }
  return res;
}
void run() {
  long long cnt = 0;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    cnt += a[i];
  }
  if (cnt == 1) {
    cout << -1;
    return;
  }
  long long ans = 1e18;
  for (int i = 2; 1ll * i * i <= cnt; i++) {
    if (cnt % i == 0) {
      ans = min(ans, gao(i));
      while (cnt % i == 0) cnt /= i;
    }
  }
  if (cnt > 1) ans = min(ans, gao(cnt));
  cout << ans << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cout << fixed << setprecision(20);
  while (cin >> n) run();
  return 0;
}
