#include <bits/stdc++.h>
using namespace std;
const long long MAX = 1000006;
long long a[MAX], n, sum, aim, fin = 9223372036854775807;
signed main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]), sum += a[i];
  if (sum == 1) {
    printf("-1");
    return 0;
  }
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i == 0) {
      while (sum % i == 0) sum /= i;
      aim = i;
      long long cnt = 0, ans = 0;
      for (long long j = 1; j <= n; j++) {
        cnt = (cnt + a[j]) % aim;
        ans += min(cnt, aim - cnt);
      }
      fin = min(fin, ans);
    }
  }
  if (sum > 1) {
    aim = sum;
    long long cnt = 0, ans = 0;
    for (long long j = 1; j <= n; j++) {
      cnt = (cnt + a[j]) % aim;
      ans += min(cnt, aim - cnt);
    }
    fin = min(fin, ans);
  }
  printf("%lld", fin);
  return 0;
}
