#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
long long a[N];
long long s[N];
long long n;
long long calc(long long x) {
  long long sum = 0, pre = 0;
  for (long long i = 1; i <= n; i++)
    pre += a[i], pre %= x, sum += min(pre, x - pre);
  return sum;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) scanf("%lld", &a[i]), s[i] = s[i - 1] + a[i];
  if (s[n] == 1)
    cout << -1 << endl;
  else {
    long long temp = s[n];
    long long ans = 1e18;
    for (long long i = 2; i * i <= temp; i++)
      if (temp % i == 0) {
        ans = min(ans, calc(i));
        while (temp % i == 0) temp /= i;
      }
    if (temp > 1) ans = min(ans, calc(temp));
    if (ans == 1e18)
      cout << -1 << endl;
    else
      printf("%lld", ans);
  }
  return 0;
}
