#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = INT_MAX;
const int mod = 1e9 + 7;
const int N = 1e6 + 10;
inline int add(int x, int y) {
  x += y;
  if (x >= mod) x -= mod;
  return x;
}
inline int mul(int x, int y) {
  x = (1LL * x * y) % mod;
  return x;
}
clock_t time_p = clock();
int a[N];
long long pref[N];
int n;
long long get(long long k) {
  long long res = 0;
  for (int i = 1; i <= n - 1; ++i) {
    res += min(pref[i] % k, k - pref[i] % k);
  }
  return res;
}
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> a[i];
  long long sum = 0;
  for (int i = 1; i <= n; ++i) sum += a[i];
  for (int i = 1; i <= n; ++i) pref[i] = pref[i - 1] + a[i];
  if (sum == 1) {
    cout << -1 << "\n";
    return 0;
  }
  long long ans = 1e18;
  for (long long i = 2; i * i <= sum; i++) {
    if (sum % i == 0) {
      while (sum % i == 0) sum /= i;
      ans = min(ans, get(i));
    }
  }
  if (sum != 1) ans = min(ans, get(sum));
  cout << ans << "\n";
  time_p = clock() - time_p;
  cerr << "\nTime Taken : " << (float)(time_p) / CLOCKS_PER_SEC << "\n";
  return 0;
}
