#include <bits/stdc++.h>
using namespace std;
int n;
int A[1000000 + 10];
int a[1000000 + 10];
long long Ans;
long long Sum = 0;
long long DP[1000000 + 10];
long long Count(int l, int r) {
  long long Re = 1e18;
  long long Now = 0;
  long long Cnt = 0;
  DP[l - 1] = 0;
  for (int i = l; i <= r; i++) {
    DP[i] = DP[i - 1] + Now;
    Now += a[i];
  }
  Now = 0;
  DP[r + 1] = 0;
  for (int i = r; i >= l; i--) {
    Now += a[i];
    Re = min(Re, DP[i] + Cnt);
    Cnt += Now;
  }
  return Re;
}
long long work(long long x) {
  long long Re = 0;
  long long Now = 0;
  long long X, Y;
  int L = 1;
  for (int i = 1; i <= n; i++) {
    a[i] = A[i] % x;
    if (Now + a[i] >= x) {
      X = x - Now;
      Y = a[i];
      a[i] = X;
      Re += Count(L, i);
      a[i] = Y - X;
      L = i;
      Now = a[i];
    } else {
      Now += a[i];
    }
  }
  return Re;
}
bool b[1000000 + 10];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &A[i]);
    Sum += A[i];
  }
  if (Sum == 1) return printf("-1"), 0;
  Ans = 1e18;
  for (long long i = 2; i <= 1000000; i++) {
    if (b[i]) continue;
    if (Sum % i == 0) {
      Ans = min(Ans, work(i));
      while (Sum % i == 0) Sum /= i;
    }
    for (long long j = i * i; j <= 1000000; j += i) b[j] = true;
  }
  if (Sum != 1) Ans = min(Ans, work(Sum));
  printf("%I64d", Ans);
  return 0;
}
