#include <bits/stdc++.h>
using namespace std;
const long double pi = 3.1415926535897932384626433832795l;
template <typename T>
inline auto sqr(T x) -> decltype(x * x) {
  return x * x;
}
template <typename T>
inline T abs(T x) {
  return x > T() ? x : -x;
}
template <typename T1, typename T2>
inline bool umx(T1& a, T2 b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <typename T1, typename T2>
inline bool umn(T1& a, T2 b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}
const int N = 1000100;
int c[N];
int copy_c[N];
int n;
long long sum;
inline int my_abs(int a) {
  if (a < 0) {
    return -a;
  }
  return a;
}
long long check(long long p) {
  long long ans = 0;
  long long cur = 0;
  int lst_idx = 0;
  for (int i = 0; i < n; ++i) {
    if (cur == 0) {
      c[i] %= p;
    }
    if (cur + c[i] >= p) {
      c[i] -= p - cur;
      long long cur1 = 0;
      int idx_to_move = i;
      for (int j = lst_idx; j < i; ++j) {
        cur1 += c[j];
        if (cur1 >= (p + 1) / 2) {
          idx_to_move = j;
          break;
        }
      }
      for (int j = int(lst_idx); j < int(i); ++j) {
        ans += 1ll * my_abs(j - idx_to_move) * c[j];
      }
      ans += (p - cur) * (i - idx_to_move);
      cur = 0;
      lst_idx = i;
      --i;
    } else {
      cur += c[i];
    }
  }
  for (int i = int(0); i < int(n); ++i) {
    c[i] = copy_c[i];
  }
  return ans;
}
int main() {
  cout.setf(ios::showpoint | ios::fixed);
  cout.precision(20);
  cin >> n;
  sum = 0;
  for (int i = int(0); i < int(n); ++i) {
    scanf("%d", &c[i]);
    copy_c[i] = c[i];
    sum += c[i];
  }
  if (sum == 1) {
    cout << -1 << endl;
    return 0;
  }
  long long ans = (1ll << 60);
  vector<long long> all_p;
  long long cursum = sum;
  for (long long i = 2; i * i <= cursum; ++i) {
    if (cursum % i == 0) {
      all_p.push_back(i);
      while (cursum % i == 0) {
        cursum /= i;
      }
    }
  }
  if (cursum > 1) {
    all_p.push_back(cursum);
  }
  assert(((int)(all_p).size()) <= 15);
  for (long long p : all_p) {
    umn(ans, check(p));
  }
  cout << ans << endl;
  return 0;
}
