#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long x = 0, f = 1;
  char ch = getchar();
  for (; ch < '0' || ch > '9'; ch = getchar())
    if (ch == '-') f = -1;
  for (; ch >= '0' && ch <= '9'; ch = getchar())
    x = (x << 1) + (x << 3) + ch - '0';
  return x * f;
}
const long long N = 1e6 + 5;
long long a[N], vis[N];
signed main() {
  long long n = read();
  long long all = 0;
  long long ans = 1LL << 60;
  for (long long i = 1; i <= n; ++i) all += (a[i] = read());
  for (long long i = 2; i < N; ++i)
    if (!vis[i])
      for (long long j = i + i; j < N; j += i) vis[j] = 1;
  for (long long i = 2; i <= (long long)sqrt(all); ++i)
    if (!vis[i] && all % i == 0) {
      while (all % i == 0) all /= i;
      long long res = 0;
      long long sum = 0;
      for (long long j = 1; j <= n; ++j) {
        (sum += a[j]) %= i;
        res += min(sum, i - sum);
      }
      ans = min(ans, res);
    }
  if (all > 1) {
    long long res = 0;
    long long sum = 0;
    for (long long j = 1; j <= n; ++j) {
      (sum += a[j]) %= all;
      res += min(sum, all - sum);
    }
    ans = min(ans, res);
  }
  if (ans == 1LL << 60)
    puts("-1");
  else
    printf("%lld\n", ans);
  return 0;
}
