#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#ifdef local
  #define readfromfile(file) freopen(file, "r", stdin)
  #define debug(...) { cerr << __LINE__ << " : \
     [" << #__VA_ARGS__ << "] = ["; err(__VA_ARGS__); cerr << "]\n";}
  template<class T>
  void err(T x) { cerr << x;}
  template<class T, class...Args>
  void err(T x, Args... args){ cerr << x << ", ";err(args...);}
#else
  #define debug(...)
  #define readfromfile(...)
  #define endl '\n'
  #define cerr if(0)cout
  #define err(...)
#endif
#define fi first
#define se second
#define empb emplace_back
#define bk back
#define ppb pop_back
#define ins insert
#define clr(a, b) memset(a, b, sizeof a)
#define rep(i, n) for(int i = 0; i < n; i++)
#define ls rt << 1
#define rs rt<<1|1
#define inf 0x3f3f3f3f
#define all(x) (x).begin(),(x).end()
typedef long long ll;
typedef vector<int> VI;
typedef pair<int, int> pii;
typedef long double ldb;
typedef complex<double> cpd;
const int N = 3e5 + 7, M = 1 << 10;
const double pi = acos(-1.0);
const int P = 7 * 17 << 23 | 1, G = 3;
const int mod = 1e9 + 7;

vector<int> getpfac(int x) {
  vector<int> pfac;
  for(int i = 2; i * i <= x; i++) {
    if(x % i == 0) {
      pfac.push_back(i);
      while(x % i == 0) x /= i;
    }
  }
  if(x != 1) pfac.push_back(x);
  return pfac;
}

ll check(int x, vector<int> &a) {
  int n = a.size();
  ll res = 0;
  for(int i = 0; i < n; i++) {
    if(a[i] == 1) {
      int j = i;
      int c = 0;
      while(j < n && c < x) {
        if(a[j] == 1 && c < x / 2) res -= j;
        else if(a[j] == 1 && c >= (x + 1) / 2) res += j;
        c += a[j] == 1; j++;
      }
      i = j - 1;
    }
  }
  return res;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  readfromfile("in.txt");
  int n; cin >> n;
  vector<int> a(n);
  int cnt = 0;
  for(int i = 0; i < n; i++) {
    cin >> a[i];
    cnt += a[i] == 1;
  }
  if(cnt == 1) return cout << -1 << endl, 0;
  int res = cnt;
//  for(int i = 2; i * i <= cnt; i++) {
//    if(cnt % i == 0) {
//      res = i; break;
//    }
//  }
  vector<int> pfac = getpfac(cnt);
  ll ans = LLONG_MAX;
  for(auto &e : pfac) {
    ans = min(ans, check(e, a));
  }
  cout << ans << endl;
  cerr << clock() << " ms\n";
  return 0;
}


#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#ifdef local
  #define readfromfile(file) freopen(file, "r", stdin)
  #define debug(...) { cerr << __LINE__ << " : \
     [" << #__VA_ARGS__ << "] = ["; err(__VA_ARGS__); cerr << "]\n";}
  template<class T>
  void err(T x) { cerr << x;}
  template<class T, class...Args>
  void err(T x, Args... args){ cerr << x << ", ";err(args...);}
#else
  #define debug(...)
  #define readfromfile(...)
  #define endl '\n'
  #define cerr if(0)cout
  #define err(...)
#endif
#define fi first
#define se second
#define empb emplace_back
#define bk back
#define ppb pop_back
#define ins insert
#define clr(a, b) memset(a, b, sizeof a)
#define rep(i, n) for(int i = 0; i < n; i++)
#define ls rt << 1
#define rs rt<<1|1
#define inf 0x3f3f3f3f
#define all(x) (x).begin(),(x).end()
typedef long long ll;
typedef vector<int> VI;
typedef pair<int, int> pii;
typedef long double ldb;
typedef complex<double> cpd;
const int N = 3e5 + 7, M = 1 << 10;
const double pi = acos(-1.0);
const int P = 7 * 17 << 23 | 1, G = 3;
const int mod = 1e9 + 7;

vector<int> getpfac(int x) {
  vector<int> pfac;
  for(int i = 2; i * i <= x; i++) {
    if(x % i == 0) {
      pfac.push_back(i);
      while(x % i == 0) x /= i;
    }
  }
  if(x != 1) pfac.push_back(x);
  return pfac;
}

int check(int x, vector<int> &a) {
  int n = a.size(), res = 0;
  for(int i = 0; i < n; i++) {
    if(a[i] == 1) {
      int j = i;
      int c = 0;
      while(j < n && c < x) {
        c += a[j] == 1; j++;
      }
      res += j - i - 1;
      i = j - 1;
    }
  }
  return res;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  readfromfile("in.txt");
  int n; cin >> n;
  vector<int> a(n);
  int cnt = 0;
  for(int i = 0; i < n; i++) {
    cin >> a[i];
    cnt += a[i] == 1;
  }
  if(cnt == 1) return cout << -1 << endl, 0;
  int res = cnt;
//  for(int i = 2; i * i <= cnt; i++) {
//    if(cnt % i == 0) {
//      res = i; break;
//    }
//  }
  vector<int> pfac = getpfac(cnt);
  int ans = INT_MAX;
  for(auto &e : pfac) {
    ans = min(ans, check(e, a));
  }
  cout << ans << endl;
  cerr << clock() << " ms\n";
  return 0;
}


#include <bits/stdc++.h>
#define R register
#define mp make_pair
#define ll long long
#define pii pair<int, int>
using namespace std;
const int N = 1100000;

int n, a[N], prime[N], ispr[N], nopr;
ll sum, ans = 1e18;

template <class T>
inline void read(T &x) {
    x = 0;
    char ch = getchar(), w = 0;
    while (!isdigit(ch)) w = (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    x = w ? -x : x;
    return;
}

inline ll calc(ll pr) {
    ll ret = 0, mid = (pr + 1) / 2, num = 0;
    for (R int i = 1; i <= n; ++i) {
        int tmp = a[i];
        if (num <= mid) {
            if (tmp >= mid - num)
                tmp -= mid - num, num = mid;
            else {
                num += tmp, ret += num;
                continue;
            }
        }
        if (num >= mid) {
            if (tmp >= pr - num)
                tmp -= pr - num, num = 0;
            else {
                num += tmp, ret += pr - num;
                continue;
            }
        }
        num = tmp % pr;
        if (num < mid) ret += num;
        else ret += pr - num;
    }
    return ret;
}

int main() {
    read(n);
    for (R int i = 1; i <= n; ++i) read(a[i]), sum += a[i];
    if (sum == 1) return printf("-1\n"), 0;
    int lim = sqrt(sum);
    for (R int i = 2; i <= lim; ++i) {
        if (!ispr[i]) prime[++nopr] = i;
        for (R int j = 1, k; j <= nopr && (k = i * prime[j]) <= lim; ++j) {
            ispr[k] = 1;
            if (i % prime[j] == 0) continue;
        }
    }
    ll tmp = sum;
    for (R int i = 1; i <= nopr; ++i) {
        if (tmp % prime[i] == 0) {
            ans = min(ans, calc(prime[i]));
            while (tmp % prime[i] == 0) tmp /= prime[i];
        }
    }
    if (tmp != 1) ans = min(ans, calc(tmp));
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
#define R register
#define mp make_pair
#define ll long long
#define pii pair<int, int>
using namespace std;
const int N = 1100000;

int n, a[N], prime[N], ispr[N], nopr;
ll sum, ans = 1e18;

template <class T>
inline void read(T &x) {
    x = 0;
    char ch = getchar(), w = 0;
    while (!isdigit(ch)) w = (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    x = w ? -x : x;
    return;
}

inline ll calc(ll pr) {
    ll ret = 0, mid = (pr + 1) / 2, num = 0;
    for (R int i = 1; i <= n; ++i) {
        int tmp = a[i];
        if (num <= mid) {
            if (tmp >= mid - num)
                tmp -= mid - num, num = mid;
            else {
                num += tmp, ret += num;
                continue;
            }
        }
        if (num >= mid) {
            if (tmp >= pr - mid)
                tmp -= pr - mid, num = 0;
            else {
                num += tmp, ret += pr - num;
                continue;
            }
        }
        num = tmp % pr;
        if (num <= mid) ret += num;
        else ret += pr - num;
    }
    return ret;
}

int main() {
    read(n);
    for (R int i = 1; i <= n; ++i) read(a[i]), sum += a[i];
    if (sum == 1) return printf("-1\n"), 0;
    int lim = sqrt(sum);
    for (R int i = 2; i <= lim; ++i) {
        if (!ispr[i]) prime[++nopr] = i;
        for (R int j = 1, k; j <= nopr && (k = i * prime[j]) <= lim; ++j) {
            ispr[k] = 1;
            if (i % prime[j] == 0) continue;
        }
    }
    ll tmp = sum;
    for (R int i = 1; i <= nopr; ++i) {
        if (tmp % prime[i] == 0) {
            ans = min(ans, calc(prime[i]));
            while (tmp % prime[i] == 0) tmp /= prime[i];
        }
    }
    if (tmp != 1) ans = min(ans, calc(tmp));
    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
#define R register
#define mp make_pair
#define ll long long
#define pii pair<int, int>
using namespace std;
const int N = 1100000;

int n, a[N], prime[N], ispr[N], nopr;
ll sum, ans = 1e18;

template <class T>
inline void read(T &x) {
    x = 0;
    char ch = getchar(), w = 0;
    while (!isdigit(ch)) w = (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    x = w ? -x : x;
    return;
}

inline ll calc(ll pr) {
    ll ret = 0, mid = (pr + 1) / 2, num = 0;
    for (R int i = 1; i <= n; ++i) {
        int tmp = a[i];
        if (num <= mid) {
            if (tmp >= mid - num)
                tmp -= mid - num, num = mid;
            else {
                num += tmp, ret += num;
                continue;
            }
        }
        if (num >= mid) {
            if (tmp >= pr - mid)
                tmp -= pr - mid, num = 0;
            else {
                num += tmp, ret += pr - num;
                continue;
            }
        }
        num = tmp % pr;
        if (num < mid) ret += num;
        else ret += pr - num;
    }
    return ret;
}

int main() {
    read(n);
    for (R int i = 1; i <= n; ++i) read(a[i]), sum += a[i];
    if (sum == 1) return printf("-1\n"), 0;
    int lim = sqrt(sum);
    for (R int i = 2; i <= lim; ++i) {
        if (!ispr[i]) prime[++nopr] = i;
        for (R int j = 1, k; j <= nopr && (k = i * prime[j]) <= lim; ++j) {
            ispr[k] = 1;
            if (i % prime[j] == 0) continue;
        }
    }
    ll tmp = sum;
    for (R int i = 1; i <= nopr; ++i) {
        if (tmp % prime[i] == 0) {
            ans = min(ans, calc(prime[i]));
            while (tmp % prime[i] == 0) tmp /= prime[i];
        }
    }
    if (tmp != 1) ans = min(ans, calc(tmp));
    cout << ans << endl;
    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;

void fac(int v, vector<int>& pr) {
  if (v == 1) return;
  // cout << v << endl;
  int f = 0;
  for (int i = 2; i*i <= v; ++i) {
    if (v%i == 0){
      f = i;
      break;
    }
  }
  if (f == 0) {
    pr.push_back(v);
    return ;
  } else {
    fac(f, pr);
    fac(v/f, pr);
  }
}

int main() {
#ifndef ONLINE_JUDGE
  freopen("input.txt","r",stdin);
  //freopen("output.txt","w",stdout);
#endif
  int n;
  cin >> n;
  // cout << n << endl;
  vector<int> a;
  vector<int> p;
  for(int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    a.push_back(x);
    // cout << x << endl;
    if (x==1)  {
      p.push_back(i);
    }
  }
  int c = p.size();
  // cout << c << endl;
  vector<int> pr;
  fac(p.size(), pr);
  if (pr.size() == 0){
    cout << "-1\n";
  } else {
  // for (auto t : pr) cout << t << " ";
  // cout << endl;
    int min_mv = 100000;
    for (auto f:pr) {
      int num = c / f;
      int mv = 0;
      for (int i = 1; i <= num; ++i) {
        mv += p[i *f - 1] - p[(i - 1) *f];
      }
      min_mv = min(mv, min_mv);
    }
    cout << min_mv << "\n";
  }
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;

void fac(int v, vector<int>& pr) {
  if (v == 1) return;
  // cout << v << endl;
  int f = 0;
  for (int i = 2; i*i <= v; ++i) {
    if (v%i == 0){
      f = i;
      break;
    }
  }
  if (f == 0) {
    pr.push_back(v);
    return ;
  } else {
    fac(f, pr);
    fac(v/f, pr);
  }
}

int main() {
#ifndef ONLINE_JUDGE
  freopen("input.txt","r",stdin);
  //freopen("output.txt","w",stdout);
#endif
  int n;
  cin >> n;
  // cout << n << endl;
  vector<int> a;
  vector<int> p;
  for(int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    a.push_back(x);
    // cout << x << endl;
    if (x==1)  {
      p.push_back(i);
    }
  }
  int c = p.size();
  // cout << c << endl;
  vector<int> pr;
  fac(p.size(), pr);
  if (pr.size() == 0){
    cout << "-1\n";
  } else {
  // for (auto t : pr) cout << t << " ";
  // cout << endl;
    int64_t min_mv = 1000000000000000;
    for (auto f:pr) {
      int num = c / f;
      int64_t mv = 0;
      for (int i = 1; i <= num; ++i) {
        int start = (i - 1) *f;
        // int end = i *f - 1;
        int mid = p[(i - 1) * f + f/2];
        for (int k = 0; k < f; ++k) {
          mv += abs(mid - p[start + k]);
        }
      }
      // cout << f << " " << mv << "\n";
      min_mv = min(mv, min_mv);
    }
    cout << min_mv << "\n";
  }
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;

void fac(int v, vector<int>& pr) {
  if (v == 1) return;
  // cout << v << endl;
  int f = 0;
  for (int i = 2; i*i <= v; ++i) {
    if (v%i == 0){
      f = i;
      break;
    }
  }
  if (f == 0) {
    pr.push_back(v);
    return ;
  } else {
    fac(f, pr);
    fac(v/f, pr);
  }
}

int main() {
#ifndef ONLINE_JUDGE
  freopen("input.txt","r",stdin);
  //freopen("output.txt","w",stdout);
#endif
  int n;
  cin >> n;
  // cout << n << endl;
  vector<int> a;
  vector<int> p;
  for(int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    a.push_back(x);
    // cout << x << endl;
    if (x==1)  {
      p.push_back(i);
    }
  }
  int c = p.size();
  // cout << c << endl;
  vector<int> pr;
  fac(p.size(), pr);
  if (pr.size() == 0){
    cout << "-1\n";
  } else {
  // for (auto t : pr) cout << t << " ";
  // cout << endl;
    int min_mv = 100000;
    for (auto f:pr) {
      int num = c / f;
      int mv = 0;
      for (int i = 1; i <= num; ++i) {
        int start = (i - 1) *f;
        // int end = i *f - 1;
        int mid = p[(i - 1) * f + f/2];
        for (int k = 0; k < f; ++k) {
          mv += abs(mid - p[start + k]);
        }
      }
      // cout << f << " " << mv << "\n";
      min_mv = min(mv, min_mv);
    }
    cout << min_mv << "\n";
  }
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;

void fac(int v, vector<int>& pr) {
  if (v == 1) return;
  // cout << v << endl;
  int sqr = (int)sqrt(v);
  int f = 0;
  for (int i = 2; i <= sqr; ++i) {
    if (v%i == 0){
      f = i;
      break;
    }
  }
  if (f == 0) {
    pr.push_back(v);
    return ;
  } else {
    fac(f, pr);
    fac(v/f, pr);
  }
}

int main() {
#ifndef ONLINE_JUDGE
  freopen("input.txt","r",stdin);
  //freopen("output.txt","w",stdout);
#endif
  int n;
  cin >> n;
  // cout << n << endl;
  vector<int> a;
  vector<int> p;
  for(int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    a.push_back(x);
    // cout << x << endl;
    if (x==1)  {
      p.push_back(i);
    }
  }
  int c = p.size();
  // cout << c << endl;
  vector<int> pr;
  fac(p.size(), pr);
  if (pr.size() == 0){
    cout << "-1\n";
  } else {
  // for (auto t : pr) cout << t << " ";
  // cout << endl;
    int min_mv = 100000;
    for (auto f:pr) {
      int num = c / f;
      int mv = 0;
      for (int i = 1; i <= num; ++i) {
        mv += p[i *f - 1] - p[(i - 1) *f];
      }
      min_mv = min(mv, min_mv);
    }
    cout << min_mv << "\n";
  }
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;

void fac(int v, vector<int>& pr) {
  if (v == 1) return;
  // cout << v << endl;
  int f = 0;
  for (int i = 2; i*i <= v; ++i) {
    if (v%i == 0){
      f = i;
      break;
    }
  }
  if (f == 0) {
    pr.push_back(v);
    return ;
  } else {
    fac(f, pr);
    fac(v/f, pr);
  }
}

int main() {
#ifndef ONLINE_JUDGE
  freopen("input.txt","r",stdin);
  //freopen("output.txt","w",stdout);
#endif
  int n;
  cin >> n;
  // cout << n << endl;
  vector<int> a;
  vector<int> p;
  for(int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    a.push_back(x);
    // cout << x << endl;
    if (x==1)  {
      p.push_back(i);
    }
  }
  int c = p.size();
  // cout << c << endl;
  vector<int> pr;
  fac(p.size(), pr);
  if (pr.size() == 0){
    cout << "-1\n";
  } else {
  // for (auto t : pr) cout << t << " ";
  // cout << endl;
    int64_t min_mv = 100000;
    for (auto f:pr) {
      int num = c / f;
      int64_t mv = 0;
      for (int i = 1; i <= num; ++i) {
        int start = (i - 1) *f;
        // int end = i *f - 1;
        int mid = p[(i - 1) * f + f/2];
        for (int k = 0; k < f; ++k) {
          mv += abs(mid - p[start + k]);
        }
      }
      // cout << f << " " << mv << "\n";
      min_mv = min(mv, min_mv);
    }
    cout << min_mv << "\n";
  }
}


#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define X first
#define Y second
typedef long long ll;

int n;
int a[100010];
int sum;

bool not_prime[1010];
ll ans = 0x7f7f7f7f7f7f7f;
bool flag;

void test(int x)
{
	flag = true;
	int val = 0; ll myans = 0;
	for (int i = 1; i <= n; i++)
	{
		if (a[i] == 1) val++;
		if (x - val < val) val = val - x;
		myans += abs(val);
	}
	ans = min(ans, myans);
}

int main()
{
	for (int i = 2; i <= 1000; i++)
	{
		if (not_prime[i]) continue;
		for (int j = i * i; j <= 1000; j += 2 * i) not_prime[j] = true;
	}

	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
		sum += a[i];
	}

	for (int i = 2; i <= 1000; i++)
		if (!not_prime[i] && sum%i == 0) test(i);
	if (!flag && sum != 1) test(sum);

	if (ans == 0x7f7f7f7f7f7f7f) puts("-1");
	else printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define X first
#define Y second
typedef long long ll;

int n;
int a[100010];
int sum;

bool not_prime[1010];
ll ans = 0x7f7f7f7f;

void test(int x)
{
	int val = 0; ll myans = 0;
	for (int i = 1; i <= n; i++)
	{
		if (a[i] == 1) val++;
		if (x - val < val) val = val - x;
		myans += abs(val);
	}
	ans = min(ans, myans);
}

int main()
{
	for (int i = 2; i <= 1000; i++)
	{
		if (not_prime[i]) continue;
		for (int j = i * i; j <= 1000; j += 2 * i) not_prime[j] = true;
	}

	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
		sum += a[i];
	}

	for (int i = 2; i <= 1000; i++)
		if (!not_prime[i] && sum%i == 0) test(i);

	if (ans == 0x7f7f7f7f) puts("-1");
	else printf("%lld\n", ans);
}


#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define X first
#define Y second
typedef long long ll;

int n;
int a[100010];
int sum;

bool not_prime[1010];
ll ans = 0x7f7f7f7f7f7f7f;

void test(int x)
{
	int val = 0; ll myans = 0;
	for (int i = 1; i <= n; i++)
	{
		if (a[i] == 1) val++;
		if (x - val < val) val = val - x;
		myans += abs(val);
	}
	ans = min(ans, myans);
}

int main()
{
	for (int i = 2; i <= 1000; i++)
	{
		if (not_prime[i]) continue;
		for (int j = i * i; j <= 1000; j += 2 * i) not_prime[j] = true;
	}

	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
		sum += a[i];
	}

	for (int i = 2; i <= 1000; i++)
		if (!not_prime[i] && sum%i == 0) test(i);

	if (ans == 0x7f7f7f7f7f7f7f) puts("-1");
	else printf("%lld\n", ans);
}


#include<iostream>
#include<string.h>
int n,a[100005],b[100005],m=0,t,c;
long long ans=0;
int prime[100000];
bool number[100005];
int main(){
	scanf("%d",&n);
	memset(b,0,sizeof(b));
	for(int i=0;i<n;i++){
		scanf("%d",&a[i]);
		if(a[i]==1){
			m++;
			b[m]=i;
		}
	}
	c=0;
    memset(number,true,sizeof(number));
    for(int i=2;i<=n&&m!=1;i++){
        if(number[i]) prime[c++]=i;
        for(int j=0;j<c&&prime[j]*i<=n;j++){
            number[prime[j]*i]=false;
            if(i%prime[j]==0) break;
        }
    }
	for(int i=0;i<c&&m!=1;i++){
		if(m%prime[i]==0){
			t=prime[i];
			break;
		}
	}
	if(m==1) ans=-1;
	else if(t%2==0){
		for(int i=1;i<=m;i=i+2){
			ans+=b[i+1]-b[i];
		}
	}
	else{
		for(int i=1;i<=m;i=i+t){
			int d=i+t/2;
			for(int j=i;j<d;j++) ans+=b[d]-b[j];
			for(int j=d+1;j<i+t;j++) ans+=b[j]-b[d];
		}
	}
	printf("%d\n",ans);
	return 0;
}


// Author: wlzhouzhuan
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define rint register int
#define rep(i, l, r) for (rint i = l; i <= r; i++)
#define per(i, l, r) for (rint i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = (x << 3) + (x << 1) + op - '0'; op = getchar(); }
  return neg * x;
}

const int N = 100005;
ll a[N], sum[N], b[N];
int n, m;
ll ans = 1e18;

int main() {
  n = read();
  for (rint i = 1; i <= n; i++) {
    a[i] = read();
    if (a[i]) sum[i] = sum[i - 1] + i;
    else sum[i] = sum[i - 1];
    if (a[i]) b[++m] = i;
  }
  for (rint k = 2; k <= m; k++) if (m % k == 0) {
    ll tar = 0ll;
    for (rint l = 1, r = k; l <= m; l += k, r += k) {
      int mid = l + r >> 1;
      tar += b[mid] * (mid - l + 1) - (sum[b[mid]] - sum[b[l] - 1]) + (sum[b[r]] - sum[b[mid]]) - b[mid] * (r - mid);
    }
    ans = min(ans, tar);
  }
  if (ans == 1e18) ans = -1;
  printf("%lld\n", ans);
  return 0;
}


#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<time.h>
#define ll long long
#define U unsigned
#define mem(x,y) memset(x,y,sizeof(x))
#define rep(x,m,n) for(int x=m;x<=n;x++)
#define All(x)  (x.begin(),x.end())
#define ls rt<<1
#define rs rt<<1|1
#define lson l,m,ls
#define rson m+1,r,rs
#define pb push_back
#define mp make_pair
#define print(x) cout<<(x)
#define pin cout<<'\n'
#define sp cout<<" "
#define println(x) cout<<(x)<<'\n'
#define read(x) cin>>(x)
#define debug cout<<"test"<<'\n'
#define test system("pause");
#define ALL(x) (x.begin(),x.end())
#define siz(x) ((int)x.size())
using namespace std;
const double eps=1e-8;
const double pi=acos(-1.0);
const ll INF=0x3f3f3f3f3f3f3f3f;
const int inf=0x3f3f3f3f;
const int N=2e5+5;
int n;
int a[N];
vector<int> e[N];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int inx[N];
ll res[N];
void INIT()
{
     //fill

//    rep(i,1,n)
//    {
//        e[i].clear();
//    }
mem(res,0);
mem(inx,0);
}
void solve()
{
    INIT();
    int sum=0;
    rep(i,1,n) read(a[i]),sum+=a[i];
    if(sum==1)
    {
        println(-1);
        return;
    }
    int x;
    for(x=2;x<=sum;x++)
    {
        if(sum%x==0) break;
    }
    int y=0;
    int cnt=0;
    ll ans=0;
    rep(i,1,n)
    {
        y+=a[i];
        if(a[i])
        {
            cnt++;
            inx[cnt]=i;
        }
        if(y==x)
        {
           for(int j=1;j<=cnt;j++)
           {
   //            cout<<inx[j]<<" ";
               res[j]=res[j-1]+inx[j];
           }
     //      pin;
           ll tmp=1e18;
           for(int j=1;j<=cnt;j++)
           {
               ll precnt=j-1,sufcnt=cnt-j;
               ll presum=precnt*inx[j]-res[j-1];
               ll sufsum=(res[cnt]-res[j])-sufcnt*inx[j];
      //         cout<<precnt<<" "<<sufcnt<<" "<<presum<<" "<<sufsum<<endl;
               tmp=min(tmp,presum+sufsum);
           }
           ans+=tmp;

           cnt=0;
        }
    }
    println(ans);
}
int main()
{
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        solve();
    }
    return 0;
}


#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<time.h>
#define ll long long
#define U unsigned
#define mem(x,y) memset(x,y,sizeof(x))
#define rep(x,m,n) for(int x=m;x<=n;x++)
#define All(x)  (x.begin(),x.end())
#define ls rt<<1
#define rs rt<<1|1
#define lson l,m,ls
#define rson m+1,r,rs
#define pb push_back
#define mp make_pair
#define print(x) cout<<(x)
#define pin cout<<'\n'
#define sp cout<<" "
#define println(x) cout<<(x)<<'\n'
#define read(x) cin>>(x)
#define debug cout<<"test"<<'\n'
#define test system("pause");
#define ALL(x) (x.begin(),x.end())
#define siz(x) ((int)x.size())
using namespace std;
const double eps=1e-8;
const double pi=acos(-1.0);
const ll INF=0x3f3f3f3f3f3f3f3f;
const int inf=0x3f3f3f3f;
const int N=2e5+5;
int n;
int a[N];
vector<int> e[N];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int inx[N];
ll res[N];
void INIT()
{
     //fill

//    rep(i,1,n)
//    {
//        e[i].clear();
//    }
mem(res,0);
mem(inx,0);
}
void solve()
{
    INIT();
    int sum=0;
    rep(i,1,n) read(a[i]),sum+=a[i];
    if(sum==1)
    {
        println(-1);
        return;
    }
    int x;
    for(x=2;x<=sum;x++)
    {
        if(sum%x==0) break;
    }
 //   println(x);
    int y=0;
    int cnt=0;
    ll ans=0;
    rep(i,1,n)
    {
        y+=a[i];
        if(a[i])
        {
            cnt++;
            inx[cnt]=i;
        }
        if(y==x)
        {
           for(int j=1;j<=cnt;j++)
           {
   //            cout<<inx[j]<<" ";
               res[j]=res[j-1]+inx[j];
           }
     //      pin;
           ll tmp=1e18;
           for(int j=1;j<=cnt;j++)
           {
               ll precnt=j-1,sufcnt=cnt-j;
               ll presum=precnt*inx[j]-res[j-1];
               ll sufsum=(res[cnt]-res[j])-sufcnt*inx[j];
 //              cout<<precnt<<" "<<sufcnt<<" "<<presum<<" "<<sufsum<<endl;
               tmp=min(tmp,presum+sufsum);
           }
           ans+=tmp;

           cnt=0;
           y=0;
        }
    }
    println(ans);
}
int main()
{
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        solve();
    }
    return 0;
}


#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<time.h>
#define ll long long
#define U unsigned
#define mem(x,y) memset(x,y,sizeof(x))
#define rep(x,m,n) for(int x=m;x<=n;x++)
#define All(x)  (x.begin(),x.end())
#define ls rt<<1
#define rs rt<<1|1
#define lson l,m,ls
#define rson m+1,r,rs
#define pb push_back
#define mp make_pair
#define print(x) cout<<(x)
#define pin cout<<'\n'
#define sp cout<<" "
#define println(x) cout<<(x)<<'\n'
#define read(x) cin>>(x)
#define debug cout<<"test"<<'\n'
#define test system("pause");
#define ALL(x) (x.begin(),x.end())
#define siz(x) ((int)x.size())
using namespace std;
const double eps=1e-8;
const double pi=acos(-1.0);
const ll INF=0x3f3f3f3f3f3f3f3f;
const int inf=0x3f3f3f3f;
const int N=2e5+5;
int n;
int a[N];
vector<int> e[N];
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int inx[N];
ll res[N];
void INIT()
{
    //fill

//    rep(i,1,n)
//    {
//        e[i].clear();
//    }
    mem(res,0);
    mem(inx,0);
}
ll check(ll x)
{
    int y=0;
    int cnt=0;
    ll ans=0;
    rep(i,1,n)
    {
        y+=a[i];
        if(a[i])
        {
            cnt++;
            inx[cnt]=i;
        }
        if(y==x)
        {
            for(int j=1; j<=cnt; j++)
            {
                //            cout<<inx[j]<<" ";
                res[j]=res[j-1]+inx[j];
            }
            //      pin;
            ll tmp=1e18;
            for(int j=1; j<=cnt; j++)
            {
                ll precnt=j-1,sufcnt=cnt-j;
                ll presum=precnt*inx[j]-res[j-1];
                ll sufsum=(res[cnt]-res[j])-sufcnt*inx[j];
//              cout<<precnt<<" "<<sufcnt<<" "<<presum<<" "<<sufsum<<endl;
                tmp=min(tmp,presum+sufsum);
            }
            ans+=tmp;

            cnt=0;
            y=0;
        }
    }
    return ans;
}
void solve()
{
    INIT();
    int sum=0;
    rep(i,1,n) read(a[i]),sum+=a[i];
    if(sum==1)
    {
        println(-1);
        return;
    }
    int x;
    ll ans=1e18;
    for(x=1; x<=sum; x++)
    {
        if(sum%x==0)
        {
            if(x>1) ans=min(ans,check(x));
            ans=min(ans,check(sum/x));
        }
    }
//   println(x);

    println(ans);
}
int main()
{
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        solve();
    }
    return 0;
}


#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<time.h>
#define ll long long
#define U unsigned
#define mem(x,y) memset(x,y,sizeof(x))
#define rep(x,m,n) for(int x=m;x<=n;x++)
#define All(x)  (x.begin(),x.end())
#define ls rt<<1
#define rs rt<<1|1
#define lson l,m,ls
#define rson m+1,r,rs
#define pb push_back
#define mp make_pair
#define print(x) cout<<(x)
#define pin cout<<'\n'
#define sp cout<<" "
#define println(x) cout<<(x)<<'\n'
#define read(x) cin>>(x)
#define debug cout<<"test"<<'\n'
#define test system("pause");
#define ALL(x) (x.begin(),x.end())
#define siz(x) ((int)x.size())
using namespace std;
const double eps=1e-8;
const double pi=acos(-1.0);
const ll INF=0x3f3f3f3f3f3f3f3f;
const int inf=0x3f3f3f3f;
const int N=2e5+5;
int n;
int a[N];
vector<int> e[N];
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int inx[N];
ll res[N];
void INIT()
{
    //fill

//    rep(i,1,n)
//    {
//        e[i].clear();
//    }
    mem(res,0);
    mem(inx,0);
}
ll check(ll x)
{
    int y=0;
    int cnt=0;
    ll ans=0;
    rep(i,1,n)
    {
        y+=a[i];
        if(a[i])
        {
            cnt++;
            inx[cnt]=i;
        }
        if(y==x)
        {
            for(int j=1; j<=cnt; j++)
            {
                //            cout<<inx[j]<<" ";
                res[j]=res[j-1]+inx[j];
            }
            //      pin;
            ll tmp=1e18;
            for(int j=1; j<=cnt; j++)
            {
                ll precnt=j-1,sufcnt=cnt-j;
                ll presum=precnt*inx[j]-res[j-1];
                ll sufsum=(res[cnt]-res[j])-sufcnt*inx[j];
//              cout<<precnt<<" "<<sufcnt<<" "<<presum<<" "<<sufsum<<endl;
                tmp=min(tmp,presum+sufsum);
            }
            ans+=tmp;

            cnt=0;
            y=0;
        }
    }
    return ans;
}
void solve()
{
    INIT();
    int sum=0;
    rep(i,1,n) read(a[i]),sum+=a[i];
    if(sum==1)
    {
        println(-1);
        return;
    }
    int x;
    ll ans=1e18;
    for(x=1; x*x<=sum; x++)
    {
        if(sum%x==0)
        {
            if(x>1) ans=min(ans,check(x));
            ans=min(ans,check(sum/x));
        }
    }
//   println(x);

    println(ans);
}
int main()
{
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        solve();
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int MAXN=1e5+5;
int a[MAXN],pos[MAXN],p;
ll sum[MAXN],loc[MAXN]; // 前缀和，坐标前缀和
int main()
{
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) {
        cin>>a[i];
        if(a[i]==1) {
            pos[++p]=i;
            sum[i]=1,loc[i]=i;
        }
    }
    for(int i=1;i<=n;i++){
        sum[i]+=sum[i-1],loc[i]+=loc[i-1];
    }
    ll ans=INF;
    for(int k=2;k<=p;k++){
        if(p%k!=0) continue;
        ll temp=0;
        for(int i=k;i<=p;i+=k){
            ll low=pos[i-k+1],high=pos[i];
            //ll mid=(low+high)>>1;
            ll mid=pos[i-k/2];
            ll cnt1=sum[mid-1]-sum[low-1],cnt2=sum[high]-sum[mid]; //统计左右有多少个数
            ll num1=loc[mid-1]-loc[low-1],num2=loc[high]-loc[mid]; //左右数坐标和
            temp+=(cnt1*mid-num1+num2-cnt2*mid);
        }
        ans=min(ans,temp);
    }
    //ans==0x3f3f3f3f?cout<<-1<<endl:cout<<ans<<endl;
    cout<<(ans==INF?-1:ans)<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int MAXN=1e5+5;
int a[MAXN],pos[MAXN],p;
int sum[MAXN],loc[MAXN]; // 前缀和，坐标前缀和
int main()
{
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) {
        cin>>a[i];
        if(a[i]==1) {
            pos[++p]=i;
            sum[i]=1,loc[i]=i;
        }
    }
    for(int i=1;i<=n;i++){
        sum[i]+=sum[i-1],loc[i]+=loc[i-1];
    }
    ll ans=INF;
    for(int k=2;k<=p;k++){
        if(p%k!=0) continue;
        ll temp=0;
        for(int i=k;i<=p;i+=k){
            int low=pos[i-k+1],high=pos[i];
            int mid=(low+high)>>1;
            int cnt1=sum[mid-1]-sum[low-1],cnt2=sum[high]-sum[mid]; //统计左右有多少个数
            int num1=loc[mid-1]-loc[low-1],num2=loc[high]-loc[mid]; //左右数坐标和
            temp+=(cnt1*mid-num1+num2-cnt2*mid);
        }
        ans=min(ans,temp);
    }
    //ans==0x3f3f3f3f?cout<<-1<<endl:cout<<ans<<endl;
    cout<<(ans==INF?-1:ans)<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int MAXN=1e5+5;
int a[MAXN],pos[MAXN],p;
ll sum[MAXN],loc[MAXN]; // 前缀和，坐标前缀和
int main()
{
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) {
        cin>>a[i];
        if(a[i]==1) {
            pos[++p]=i;
            sum[i]=1,loc[i]=i;
        }
    }
    for(int i=1;i<=n;i++){
        sum[i]+=sum[i-1],loc[i]+=loc[i-1];
    }
    ll ans=INF;
    for(int k=2;k<=p;k++){
        if(p%k!=0) continue;
        ll temp=0;
        for(int i=k;i<=p;i+=k){
            ll low=pos[i-k+1],high=pos[i];
            ll mid=(low+high)>>1;
            ll cnt1=sum[mid-1]-sum[low-1],cnt2=sum[high]-sum[mid]; //统计左右有多少个数
            ll num1=loc[mid-1]-loc[low-1],num2=loc[high]-loc[mid]; //左右数坐标和
            temp+=(cnt1*mid-num1+num2-cnt2*mid);
        }
        ans=min(ans,temp);
    }
    //ans==0x3f3f3f3f?cout<<-1<<endl:cout<<ans<<endl;
    cout<<(ans==INF?-1:ans)<<endl;
}


#include <bits/stdc++.h>
using namespace std;
const int MAXN=1e5+5;
int a[MAXN],pos[MAXN],p;
int sum[MAXN],loc[MAXN]; // 前缀和，坐标前缀和
int main()
{
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) {
        cin>>a[i];
        if(a[i]==1) {
            pos[++p]=i;
            sum[i]=1,loc[i]=i;
        }
    }
    for(int i=1;i<=n;i++){
        sum[i]+=sum[i-1],loc[i]+=loc[i-1];
    }
    int ans=0x3f3f3f3f,ts1;
    for(int k=2;k<=p;k++){
        if(p%k!=0) continue;
        int temp=0;
        for(int i=k;i<=p;i+=k){
            int low=pos[i-k+1],high=pos[i];
            int mid=(low+high)>>1;
            int cnt1=sum[mid-1]-sum[low-1],cnt2=sum[high]-sum[mid]; //统计左右有多少个数
            int num1=loc[mid-1]-loc[low-1],num2=loc[high]-loc[mid]; //左右数坐标和
            temp+=(cnt1*mid-num1+num2-cnt2*mid);
        }
        if(temp<ans) ts1=k;
        ans=min(ans,temp);
    }
    //ans==0x3f3f3f3f?cout<<-1<<endl:cout<<ans<<endl;
    cout<<(ans==0x3f3f3f3f?-1:ans)<<endl;
}


#include <bits/stdc++.h>
using namespace std;

const int Maxn = 100005;
int n, a[Maxn], ct = 1, pos[Maxn], bel[Maxn], now;
long long mini = 0x3f3f3f3f3f3f3f3fLL, ans, sum;
void work(int target)
{
	ans = now = 0;
	ct = 1;
	for (int i = 1; i <= n; i++)
	{
		bel[i] = ct;
		now += a[i];
		if (now == target / 2 + 1) pos[ct] = i;
		if (now == target) now = 0, ct++;
	}
	for (int i = 1; i <= n; i++)
		if (a[i]) ans += abs(i - pos[bel[i]]);
	mini = min(mini, ans);
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]), sum += a[i];
	if (sum == 1)
	{
		printf("-1");
		return 0;
	}
	int maxi = sqrt(sum);
	for (int i = 2; i <= maxi; i++)
		if (sum % i == 0)
		{
			work(i);
			while (sum % i == 0) sum /= i;
		}
	if (sum != 1)
		work(sum);
	printf("%lld", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int Maxn = 100005;
int n, a[Maxn], ct = 1, pos[Maxn], bel[Maxn], now;
long long mini = 0x3f3f3f3f, ans, sum;
void work(int target)
{
	ans = now = 0;
	ct = 1;
	for (int i = 1; i <= n; i++)
	{
		bel[i] = ct;
		now += a[i];
		if (now == target / 2 + 1) pos[ct] = i;
		if (now == target) now = 0, ct++;
	}
	for (int i = 1; i <= n; i++)
		if (a[i]) ans += abs(i - pos[bel[i]]);
	mini = min(mini, ans);
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]), sum += a[i];
	if (sum == 1)
	{
		printf("-1");
		return 0;
	}
	int maxi = sqrt(sum);
	for (int i = 2; i <= maxi; i++)
		if (sum % i == 0)
		{
			work(i);
			while (sum % i == 0) sum /= i;
		}
	if (sum != 1)
		work(sum);
	printf("%lld", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int Maxn = 100005;
int n, a[Maxn], ct = 1, pos[Maxn], bel[Maxn], now;
long long mini = 0x3f3f3f3f3f3f3f3fLL, ans, sum;
void work(int target)
{
	memset(pos, 0, sizeof(pos));
	ans = now = 0;
	ct = 1;
	for (int i = 1; i <= n; i++)
	{
		bel[i] = ct;
		now += a[i];
		if (now == target / 2 + 1 && !pos[ct]) pos[ct] = i;
		if (now == target) now = 0, ct++;
	}
	for (int i = 1; i <= n; i++)
		if (a[i]) ans += abs(i - pos[bel[i]]);
	mini = min(mini, ans);
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]), sum += a[i];
	if (sum == 1)
	{
		printf("-1");
		return 0;
	}
	int maxi = sqrt(sum);
	for (int i = 2; i <= maxi; i++)
		if (sum % i == 0)
		{
			work(i);
			while (sum % i == 0) sum /= i;
		}
	if (sum != 1)
		work(sum);
	printf("%lld", mini);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int Maxn = 100005;
int n, a[Maxn], ct = 1, pos[Maxn], bel[Maxn], now;
long long mini = 0x3f3f3f3f3f3f3f3fLL, ans, sum;
void work(int target)
{
	ans = now = 0;
	ct = 1;
	for (int i = 1; i <= n; i++)
	{
		bel[i] = ct;
		now += a[i];
		if (now == target / 2 + 1) pos[ct] = i;
		if (now == target) now = 0, ct++;
	}
	for (int i = 1; i <= n; i++)
		if (a[i]) ans += abs(i - pos[bel[i]]);
	mini = min(mini, ans);
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]), sum += a[i];
	if (sum == 1)
	{
		printf("-1");
		return 0;
	}
	int maxi = sqrt(sum);
	for (int i = 2; i <= maxi; i++)
		if (sum % i == 0)
		{
			work(i);
			while (sum % i == 0) sum /= i;
		}
	if (sum != 1)
		work(sum);
	printf("%lld", mini);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int Maxn = 100005;
int n, a[Maxn], target, _cnt, ct = 1, pos[Maxn], bel[Maxn], now;
long long ans, sum;
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d", &a[i]), sum += a[i];
	int maxi = sqrt(sum);
	target = sum;
	for (int i = 2; i <= maxi; i++)
		if (sum % i == 0)
		{
			target = i;
			break;
		}
	if (target == 1)
	{
		printf("-1");
		return 0;
	}
	for (int i = 1; i <= n; i++)
	{
		bel[i] = ct;
		_cnt += a[i];
		if (_cnt == target / 2 + 1) pos[ct] = i;
		now += a[i];
		if (now == target) now = 0, ct++, _cnt = 0;
	}
	for (int i = 1; i <= n; i++)
		if (a[i]) ans += abs(i - pos[bel[i]]);
	printf("%lld", ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e5+5;

vector<int>P;

int A[maxn];

int M[maxn];

int main(){

    ios_base::sync_with_stdio(0);
    cin.tie(0);

 //   freopen ( "a.in", "r", stdin );

    int n;
    cin>>n;

    int S = 0;

    for( int i = 1; i <= n; i++ ){
        cin>>A[i];
        S += A[i];
    }

    if ( S == 1 ){
        cout<<"-1";
        return 0;
    }
    int ts = S;
    for ( int i = 2; i <= S; i++ ){
         if ( ts % i == 0 ){
             P.push_back(i);
         }
         while ( ts % i == 0 )ts /= i;
    }
    if ( ts != 1 )P.push_back(ts);

    int sol = (1<<30);
    int c = 0;
    for ( auto x : P ){
         int ts = 0;
         int pos = 1;
         int tsol = 0;
         while ( pos <= n ){
                ts += A[pos];
                if ( A[pos] == 1 ){
                    c++;
                    M[c] = pos;
                }
                pos++;
                if ( ts == x ){
                    for ( int i = 1; i <= c; i++ ){
                         int mid;
                         if ( c % 2 == 0 )
                             mid = c/2;
                         else mid = c/2+1;
                         tsol += abs ( M[mid] - M[i] );
                    }
                    c = 0;
                    ts = 0;
                }
         }
         sol = min ( sol, tsol );
    }

    cout<<sol;

return 0;
}


#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e5+5;

vector<int>P;

int A[maxn];

int M[maxn];

int main(){

    ios_base::sync_with_stdio(0);
    cin.tie(0);

    //freopen ( "a.in", "r", stdin );

    int n;
    cin>>n;

    int S = 0;

    for( int i = 1; i <= n; i++ ){
        cin>>A[i];
        S += A[i];
    }

    if ( S == 1 ){
        cout<<"-1";
        return 0;
    }
    int ts = S;
    for ( int i = 2; i <= S; i++ ){
         if ( ts % i == 0 ){
             P.push_back(i);
         }
         while ( ts % i == 0 )ts /= i;
    }
    if ( ts != 1 )P.push_back(ts);

    int sol = (1<<30);
    int c = 0;
    for ( auto x : P ){
         int ts = 0;
         int pos = 1;
         int tsol = 0;
         while ( pos <= n ){
                ts += A[pos];
                if ( A[pos] == 1 ){
                    c++;
                    M[c] = pos;
                }
                pos++;
                if ( ts == x ){
                    for ( int i = 1; i <= c; i++ ){
                         int mid;
                         if ( c % 2 == 0 )
                             mid = c/2;
                         else mid = c/2+1;
                         tsol += abs ( M[mid] - M[i] );
                    }
                    sol = min ( sol, tsol );
                    tsol = 0;
                    c = 0;
                    ts = 0;
                }
         }
    }

    cout<<sol;

return 0;
}


#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxn = 1e5+5;

vector<ll>P;

ll A[maxn];

ll M[maxn];

int main(){

    ios_base::sync_with_stdio(0);
    cin.tie(0);

  //  freopen ( "a.in", "r", stdin );

    int n;
    cin>>n;

    ll S = 0;

    for( int i = 1; i <= n; i++ ){
        cin>>A[i];
        S += A[i];
    }

    if ( S == 1LL ){
        cout<<"-1";
        return 0;
    }
    ll ts = S;
    for ( ll i = 2; i <= S; i++ ){
         if ( ts % i == 0 ){
             P.push_back(i);
         }
         while ( ts % i == 0 )ts /= i;
    }
    if ( ts != 1 )P.push_back(ts);

    ll sol = 10000000000000006LL;
    int c = 0;
    for ( auto x : P ){
         ll ts = 0;
         ll pos = 1;
         ll tsol = 0;
         while ( pos <= n ){
                ts += A[pos];
                if ( A[pos] == 1 ){
                    c++;
                    M[c] = pos;
                }
                pos++;
                if ( ts == x ){
                    for ( int i = 1; i <= c; i++ ){
                         int mid;
                         if ( c % 2 == 0 )
                             mid = c/2;
                         else mid = c/2+1;
                         tsol += abs ( M[mid] - M[i] );
                    }
                    c = 0;
                    ts = 0;
                }
         }
         sol = min ( sol, tsol );
    }

    cout<<sol;

return 0;
}


/*...Part - 01...*/

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <iterator>
#include <bitset>
#include <assert.h>
#include <new>
#include <sstream>
//#include <bits/stdc++.h>
using namespace std ;

/*...Part - 02...*/

typedef long long               ll ;
typedef long double             ld ;
typedef unsigned long long      ull ;
typedef pair<int, int>           pii ;
typedef pair<ll, ll>             pll ;
typedef vector<int>             vi ;
typedef vector<ll>              vll ;
typedef vector<vector<int>>     vvi ;

/* Input Section */

template <typename T> inline void Int(T &a) {
    bool minus = false; a = 0; char ch = getchar();
    while (true) { if (ch == '-' or (ch >= '0' && ch <= '9')) break; ch = getchar(); }
    if (ch == '-') minus = true; else a = ch - '0';
    while (true) { ch = getchar(); if (ch < '0' || ch > '9') break; a = a * 10 + (ch - '0'); }
    if (minus)a *= -1 ;
}
template < typename T > inline void Int(T &a, T &b) {Int(a), Int(b) ;}
template < typename T > inline void Int(T &a, T &b, T&c) {Int(a, b), Int(c) ;}
template < typename T > inline void Int(T &a, T &b, T&c, T& d) {Int(a, b), Int(c, d) ;}

/*...Part - 03...*/
/*....Debugger....*/

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {cout << endl ;}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ' ' ;
    err(++it, args...);
}

/*...Part - 04...*/
/*...Needed to change according to problem requirements...*/

const int N          = (int)2e5 + 5 ;
const int maxN       = (int)1e6 + 6 ;
const ll  Mod        = (ll)1e9 + 7 ;
const int inf        = (int)2e9 ;
const ll  Inf        = (ll)1e18 ;
const int mod        = (int)1e9 + 7 ;

/*..........................................................*/
/*...Part - 05...*/

#define     debug(x)    cerr << #x << " = " << x << '\n' ;
#define     rep(i,b,e)  for(__typeof(e) i = (b) ; i != (e + 1) - 2 * ((b) > (e))  ; i += 1 - 2 * ((b) > (e)))
#define     all(x)      x.begin() , x.end()
#define     rall(x)     x.rbegin() , x.rend()
#define     sz(x)       (int)x.size()
#define     ff          first
#define     ss          second
#define     pb          push_back
#define     eb          emplace_back
#define     mem(a)      memset(a , 0 ,sizeof a)
#define     memn(a)     memset(a , -1 ,sizeof a)
#define     Fread      freopen("input.txt","r",stdin)
#define     Fwrite     freopen("output.txt","w",stdout)

inline int add(int a, int b, int mod) {a += b ; return a >= mod ? a - mod : a ;}
inline int sub(int a, int b, int mod) {a -= b ; return a < 0 ? a + mod : a ;}
inline int mul(int a, int b, int mod) {return (ll)a * b % mod ;}

/*...Part - 06...*/
/*...... ! Code start from here ! ......*/

int getMinFactor(int n) {
    for (int i = 2 ; i * i <= n ; ++i) {
        if (n % i == 0)return i ;
    }
    return n ;
}

int main() {
    int test = 1 , tc = 0 ;
    //Int(test) ;
    while (test--) {
        int n ; Int(n) ;
        vi a(n + 1) ;
        int sum = 0 ;
        for (int i = 1 ; i <= n ; ++i)Int(a[i]), sum += a[i] ;
        int k = getMinFactor(sum) ;
        if (k <= 1)return puts("-1"), 0 ;
        assert(sum % k == 0 and k > 1) ;
        int i = 1 ;
        ll res = 0 ;
        while (i <= n) {
            int cnt = 0 ;
            vi v ;
            while (i <= n and cnt < k) {
                if (a[i])v.pb(i), ++cnt ;
                ++i ;
            }
            if (i > n and !cnt)break ;
            //error(sz(v), k, cnt, i)
            assert(sz(v) == k) ;
            int mid = k / 2 , mid1 = mid ;
            ll x = 0 , y = 0 ;
            if (k % 2 == 0)mid1 = mid - 1 ;
            for (int j : v) {
                x += 1LL * abs(v[mid] - j) ;
                y += 1LL * abs(v[mid1] - j) ;
            }
            res += 1LL * min(x, y) ;
        }
        cout << res << '\n' ;
    }
    return 0 ;
}

/*...Always look at the part - 04...*/
/*...............END................*/


/*...Part - 01...*/

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <iterator>
#include <bitset>
#include <assert.h>
#include <new>
#include <sstream>
//#include <bits/stdc++.h>
using namespace std ;

/*...Part - 02...*/

typedef long long               ll ;
typedef long double             ld ;
typedef unsigned long long      ull ;
typedef pair<int, int>           pii ;
typedef pair<ll, ll>             pll ;
typedef vector<int>             vi ;
typedef vector<ll>              vll ;
typedef vector<vector<int>>     vvi ;

/* Input Section */

template <typename T> inline void Int(T &a) {
    bool minus = false; a = 0; char ch = getchar();
    while (true) { if (ch == '-' or (ch >= '0' && ch <= '9')) break; ch = getchar(); }
    if (ch == '-') minus = true; else a = ch - '0';
    while (true) { ch = getchar(); if (ch < '0' || ch > '9') break; a = a * 10 + (ch - '0'); }
    if (minus)a *= -1 ;
}
template < typename T > inline void Int(T &a, T &b) {Int(a), Int(b) ;}
template < typename T > inline void Int(T &a, T &b, T&c) {Int(a, b), Int(c) ;}
template < typename T > inline void Int(T &a, T &b, T&c, T& d) {Int(a, b), Int(c, d) ;}

/*...Part - 03...*/
/*....Debugger....*/

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {cout << endl ;}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ' ' ;
    err(++it, args...);
}

/*...Part - 04...*/
/*...Needed to change according to problem requirements...*/

const int N          = (int)2e5 + 5 ;
const int maxN       = (int)1e6 + 6 ;
const ll  Mod        = (ll)1e9 + 7 ;
const int inf        = (int)2e9 ;
const ll  Inf        = (ll)1e18 ;
const int mod        = (int)1e9 + 7 ;

/*..........................................................*/
/*...Part - 05...*/

#define     debug(x)    cerr << #x << " = " << x << '\n' ;
#define     rep(i,b,e)  for(__typeof(e) i = (b) ; i != (e + 1) - 2 * ((b) > (e))  ; i += 1 - 2 * ((b) > (e)))
#define     all(x)      x.begin() , x.end()
#define     rall(x)     x.rbegin() , x.rend()
#define     sz(x)       (int)x.size()
#define     ff          first
#define     ss          second
#define     pb          push_back
#define     eb          emplace_back
#define     mem(a)      memset(a , 0 ,sizeof a)
#define     memn(a)     memset(a , -1 ,sizeof a)
#define     Fread      freopen("input.txt","r",stdin)
#define     Fwrite     freopen("output.txt","w",stdout)

inline int add(int a, int b, int mod) {a += b ; return a >= mod ? a - mod : a ;}
inline int sub(int a, int b, int mod) {a -= b ; return a < 0 ? a + mod : a ;}
inline int mul(int a, int b, int mod) {return (ll)a * b % mod ;}

/*...Part - 06...*/
/*...... ! Code start from here ! ......*/

int getMinFactor(int n) {
    for (int i = 2 ; i * i <= n ; ++i) {
        if (n % i == 0)return i ;
    }
    return n ;
}

int main() {
    int test = 1 , tc = 0 ;
    //Int(test) ;
    while (test--) {
        int n ; Int(n) ;
        vi a(n + 1) ;
        int sum = 0 ;
        for (int i = 1 ; i <= n ; ++i)Int(a[i]), sum += a[i] ;
        int k = getMinFactor(sum) ;
        if (k <= 1)return puts("-1"), 0 ;
        assert(sum % k == 0 and k > 1) ;
        int i = 1 ;
        ll res = 0 ;
        while(i <= n){
            int cnt = 0 ;
            vi v ;
            while(i <= n and cnt < k){
                if(a[i])v.pb(i), ++cnt ;
                ++i ;
            }
            if(i > n)break ;
            //error(sz(v), k, cnt)
            assert(sz(v) == k) ;
            int mid = k / 2 , mid1 = mid ;
            ll x = 0 , y = 0 ;
            if(k % 2 == 0)mid1 = mid - 1 ;
            for(int j : v){
                x += 1LL * abs(v[mid] - j) ;
                y += 1LL * abs(v[mid1] - j) ;
            }
            res += 1LL * min(x, y) ;
        }
        cout << res << '\n' ;
    }
    return 0 ;
}

/*...Always look at the part - 04...*/
/*...............END................*/


/*...Part - 01...*/

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <iterator>
#include <bitset>
#include <assert.h>
#include <new>
#include <sstream>
//#include <bits/stdc++.h>
using namespace std ;

/*...Part - 02...*/

typedef long long               ll ;
typedef long double             ld ;
typedef unsigned long long      ull ;
typedef pair<int, int>           pii ;
typedef pair<ll, ll>             pll ;
typedef vector<int>             vi ;
typedef vector<ll>              vll ;
typedef vector<vector<int>>     vvi ;

/* Input Section */

template <typename T> inline void Int(T &a) {
    bool minus = false; a = 0; char ch = getchar();
    while (true) { if (ch == '-' or (ch >= '0' && ch <= '9')) break; ch = getchar(); }
    if (ch == '-') minus = true; else a = ch - '0';
    while (true) { ch = getchar(); if (ch < '0' || ch > '9') break; a = a * 10 + (ch - '0'); }
    if (minus)a *= -1 ;
}
template < typename T > inline void Int(T &a, T &b) {Int(a), Int(b) ;}
template < typename T > inline void Int(T &a, T &b, T&c) {Int(a, b), Int(c) ;}
template < typename T > inline void Int(T &a, T &b, T&c, T& d) {Int(a, b), Int(c, d) ;}

/*...Part - 03...*/
/*....Debugger....*/

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {cout << endl ;}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ' ' ;
    err(++it, args...);
}

/*...Part - 04...*/
/*...Needed to change according to problem requirements...*/

const int N          = (int)2e5 + 5 ;
const int maxN       = (int)1e6 + 6 ;
const ll  Mod        = (ll)1e9 + 7 ;
const int inf        = (int)2e9 ;
const ll  Inf        = (ll)1e18 ;
const int mod        = (int)1e9 + 7 ;

/*..........................................................*/
/*...Part - 05...*/

#define     debug(x)    cerr << #x << " = " << x << '\n' ;
#define     rep(i,b,e)  for(__typeof(e) i = (b) ; i != (e + 1) - 2 * ((b) > (e))  ; i += 1 - 2 * ((b) > (e)))
#define     all(x)      x.begin() , x.end()
#define     rall(x)     x.rbegin() , x.rend()
#define     sz(x)       (int)x.size()
#define     ff          first
#define     ss          second
#define     pb          push_back
#define     eb          emplace_back
#define     mem(a)      memset(a , 0 ,sizeof a)
#define     memn(a)     memset(a , -1 ,sizeof a)
#define     Fread      freopen("input.txt","r",stdin)
#define     Fwrite     freopen("output.txt","w",stdout)

inline int add(int a, int b, int mod) {a += b ; return a >= mod ? a - mod : a ;}
inline int sub(int a, int b, int mod) {a -= b ; return a < 0 ? a + mod : a ;}
inline int mul(int a, int b, int mod) {return (ll)a * b % mod ;}

/*...Part - 06...*/
/*...... ! Code start from here ! ......*/

int a[N] ;

ll getResult(int n, int k) {
    int i = 1 ;
    ll res = 0 ;
    while (i <= n) {
        int cnt = 0 ;
        vi v ;
        while (i <= n and cnt < k) {
            if (a[i])v.pb(i), ++cnt ;
            ++i ;
        }
        if (i > n and !cnt)break ;
        //error(sz(v), k, cnt, i)
        assert(sz(v) == k) ;
        int mid = k / 2 , mid1 = mid ;
        ll x = 0 , y = 0 ;
        if (k % 2 == 0)mid1 = mid - 1 ;
        for (int j : v) {
            x += 1LL * abs(v[mid] - j) ;
            y += 1LL * abs(v[mid1] - j) ;
        }
        res += 1LL * min(x, y) ;
    }
    return res ;
}

int main() {
    int test = 1 , tc = 0 ;
    //Int(test) ;
    while (test--) {
        int n ; Int(n) ;
        int sum = 0 ;
        for (int i = 1 ; i <= n ; ++i)Int(a[i]), sum += a[i] ;
        if (sum <= 1)return puts("-1"), 0 ;
        ll res = Inf ;
        for (int i = 2 ; i * i <= sum ; ++i) {
            if (sum % i == 0) {
                res = min(res, getResult(n, i)) ;
                res = min(res, getResult(n, sum/i)) ;
            }
        }
        res = min(res, getResult(n, sum)) ;
        cout << res << '\n' ;
    }
    return 0 ;
}

/*...Always look at the part - 04...*/
/*...............END................*/


/*...Part - 01...*/

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <iterator>
#include <bitset>
#include <assert.h>
#include <new>
#include <sstream>
//#include <bits/stdc++.h>
using namespace std ;

/*...Part - 02...*/

typedef long long               ll ;
typedef long double             ld ;
typedef unsigned long long      ull ;
typedef pair<int, int>           pii ;
typedef pair<ll, ll>             pll ;
typedef vector<int>             vi ;
typedef vector<ll>              vll ;
typedef vector<vector<int>>     vvi ;

/* Input Section */

template <typename T> inline void Int(T &a) {
    bool minus = false; a = 0; char ch = getchar();
    while (true) { if (ch == '-' or (ch >= '0' && ch <= '9')) break; ch = getchar(); }
    if (ch == '-') minus = true; else a = ch - '0';
    while (true) { ch = getchar(); if (ch < '0' || ch > '9') break; a = a * 10 + (ch - '0'); }
    if (minus)a *= -1 ;
}
template < typename T > inline void Int(T &a, T &b) {Int(a), Int(b) ;}
template < typename T > inline void Int(T &a, T &b, T&c) {Int(a, b), Int(c) ;}
template < typename T > inline void Int(T &a, T &b, T&c, T& d) {Int(a, b), Int(c, d) ;}

/*...Part - 03...*/
/*....Debugger....*/

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {cout << endl ;}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ' ' ;
    err(++it, args...);
}

/*...Part - 04...*/
/*...Needed to change according to problem requirements...*/

const int N          = (int)2e5 + 5 ;
const int maxN       = (int)1e6 + 6 ;
const ll  Mod        = (ll)1e9 + 7 ;
const int inf        = (int)2e9 ;
const ll  Inf        = (ll)1e18 ;
const int mod        = (int)1e9 + 7 ;

/*..........................................................*/
/*...Part - 05...*/

#define     debug(x)    cerr << #x << " = " << x << '\n' ;
#define     rep(i,b,e)  for(__typeof(e) i = (b) ; i != (e + 1) - 2 * ((b) > (e))  ; i += 1 - 2 * ((b) > (e)))
#define     all(x)      x.begin() , x.end()
#define     rall(x)     x.rbegin() , x.rend()
#define     sz(x)       (int)x.size()
#define     ff          first
#define     ss          second
#define     pb          push_back
#define     eb          emplace_back
#define     mem(a)      memset(a , 0 ,sizeof a)
#define     memn(a)     memset(a , -1 ,sizeof a)
#define     Fread      freopen("input.txt","r",stdin)
#define     Fwrite     freopen("output.txt","w",stdout)

inline int add(int a, int b, int mod) {a += b ; return a >= mod ? a - mod : a ;}
inline int sub(int a, int b, int mod) {a -= b ; return a < 0 ? a + mod : a ;}
inline int mul(int a, int b, int mod) {return (ll)a * b % mod ;}

/*...Part - 06...*/
/*...... ! Code start from here ! ......*/

int getMinFactor(int n) {
    for (int i = 2 ; i * i <= n ; ++i) {
        if (n % i == 0)return i ;
    }
    return n ;
}

int main() {
    int test = 1 , tc = 0 ;
    //Int(test) ;
    while (test--) {
        int n ; Int(n) ;
        vi a(n + 1) ;
        int sum = 0 ;
        for (int i = 1 ; i <= n ; ++i)Int(a[i]), sum += a[i] ;
        int k = getMinFactor(sum) ;
        if (k <= 1)return puts("-1"), 0 ;
        assert(sum % k == 0 and k > 1) ;
        int i = 1 ;
        ll res = 0 ;
        while(i <= n){
            int cnt = 0 ;
            vi v ;
            while(i <= n and cnt < k){
                if(a[i])v.pb(i), ++cnt ;
                ++i ;
            }
            assert(sz(v) == k) ;
            int mid = k / 2 , mid1 = mid ;
            ll x = 0 , y = 0 ;
            if(k % 2 == 0)mid1 = mid - 1 ;
            for(int j : v){
                x += 1LL * abs(v[mid] - j) ;
                y += 1LL * abs(v[mid1] - j) ;
            }
            res += 1LL * min(x, y) ;
        }
        cout << res << '\n' ;
    }
    return 0 ;
}

/*...Always look at the part - 04...*/
/*...............END................*/


#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>

/*
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

typedef tree<
int, //key
null_type, // value
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;

 ordered_set X;
 X.insert(1);
 X.find_by_order(1);
 X.order_of_key(-5);
*/

#define INF 1000000000000000000LL
#define FOR(i, a, b) for (int i = int(a); i < int(b); i++)
#define FORC(cont, it) \
  for (decltype((cont).begin()) it = (cont).begin(); it != (cont).end(); it++)
#define pb push_back
#define _                                               \
  if (argc == 2 && ((string)argv[1]) == "USE_IO_FILES") \
    freopen("in.txt", "r", stdin), freopen("out.txt", "w", stdout);

using namespace std;

typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> vvi;

#define maxN 1000000
#define maxA 1000000

int N;
ll a[maxN], t[maxN];

ll solve(ll p) {
  FOR(i, 0, N) { t[i] = a[i] % p; }
  ll ret = 0;
  ll ac = 0, sc = 0;
  FOR(i, 0, N) {
    if (ac + t[i] >= p) {
      int j = i;
      ll rr = INF;
      ll tsc = 0, tac = p - ac;
      ll np = ac - p;
      while (tac <= p) {
        rr = min(rr, sc + tsc);
        j--;
        if (j == -1) break;
        sc -= ac;
        ac -= t[j];
        tsc += tac;
        tac += t[j];
      }
      ret += rr;
      t[i] += np;
      ac = t[i];
      sc = t[i];
    } else {
      ac += t[i];
      sc += ac;
    }
  }
  return ret;
}

int main(int argc, char *argv[]) {
  _;
  while (scanf("%d", &N) != EOF) {
    ll s = 0;
    FOR(i, 0, N) {
      scanf("%lld", a + i);
      s += a[i];
    }
    vector<ll> primes;
    FOR(i, 2, maxA) {
      if (s % i == 0) {
        primes.push_back(i);
        while (s % i == 0) s /= i;
      }
    }
    if (s != 1) primes.push_back(s);
    ll ans = INF;
    FOR(i, 0, primes.size()) { ans = min(ans, solve(primes[i])); }
    if (ans == INF) ans = -1;
    printf("%lld\n", ans);
  }
  return 0;
}


#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>

/*
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

typedef tree<
int, //key
null_type, // value
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;

 ordered_set X;
 X.insert(1);
 X.find_by_order(1);
 X.order_of_key(-5);
*/

#define INF 1000000000000000000LL
#define FOR(i, a, b) for (int i = int(a); i < int(b); i++)
#define FORC(cont, it) \
  for (decltype((cont).begin()) it = (cont).begin(); it != (cont).end(); it++)
#define pb push_back
#define _                                               \
  if (argc == 2 && ((string)argv[1]) == "USE_IO_FILES") \
    freopen("in.txt", "r", stdin), freopen("out.txt", "w", stdout);

using namespace std;

typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<vi> vvi;

#define maxN 1000000
#define maxA 1000000

int N;
ll a[maxN], t[maxN];

ll solve(ll p) {
  FOR(i, 0, N) { t[i] = a[i] % p; }
  ll ret = 0;
  ll ac = 0, sc = 0;
  FOR(i, 0, N) {
    if (ac + t[i] >= p) {
      int j = i;
      ll rr = INF;
      ll tsc = 0, tac = p - ac;
      while (tac <= p) {
        rr = min(rr, sc + tsc);
        j--;
        sc -= ac;
        ac -= t[j];
        tsc += tac;
        tac += t[j];
      }
      ret += rr;
      t[i] += ac - p;
      ac = t[i];
      sc = 0;
    } else {
      ac += t[i];
      sc += ac;
    }
  }
  return ret;
}

int main(int argc, char *argv[]) {
  _;
  while (scanf("%d", &N) != EOF) {
    ll s = 0;
    FOR(i, 0, N) {
      scanf("%lld", a + i);
      s += a[i];
    }
    vector<ll> primes;
    FOR(i, 2, maxA) {
      if (s % i == 0) {
        primes.push_back(i);
        while (s % i == 0) s /= i;
      }
    }
    if (s != 1) primes.push_back(s);
    ll ans = INF;
    FOR(i, 0, primes.size()) { ans = min(ans, solve(primes[i])); }
    if (ans == INF) ans = -1;
    printf("%lld\n", ans);
  }
  return 0;
}


#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
typedef long long ll;
const int N = 1e5+5, M = 85;
string T = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int main()
{
	int n;
	cin >> n;
	int a[n];
	for(int i=0; i<n; i++) cin >> a[i];
	int cnt = count(a, a+n, 1);
	if(cnt%2 == 1) cout << -1 << endl;
	else
	{
		int mn = n, mx = 0;
		for(int i=0; i<n; i++)
		{
			if(a[i] == 1) mn = min(mn, i), mx = max(mx, i);
		}
		cout << mx-mn << endl;
	}
}


#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
typedef long long ll;
const int N = 1e6+5, M = 85;
ll n, a[N], b[N];
ll sol(ll x)
{
	ll ret = 0, cur = 0, l = 0, cnt = 0;

	for(int i=0; i<n; i++)
	{
		cnt += a[i];
		if(cnt >= x)
		{
			ll rem = cnt%x;
			cnt -= rem;
			ll cmt = 0;
			int mid = 0;
			a[i] -= rem;
			for(int j=l; j<=i; j++)
			{
				cmt += a[j];
				if(cmt*2 >= cnt)
				{
					mid = j;
					break;
				}
			}
			for(int j=l; j<=i; j++)
			{
				ret += a[j]*abs(mid-j);
			}
			//cout << i << " " << cnt << " " << mid << " " << rem << " " << ret << endl;
			a[i] = rem;
			cnt = rem;
			l = i;
		}
	}
	for(int i=0; i<n; i++) a[i] = b[i];
	return ret;
}
int main()
{
	cin >> n;
	for(int i=0; i<n; i++) cin >> a[i], b[i] = a[i];
	ll cnt = 0;
	for(int i=0; i<n; i++) cnt += a[i];
	if(cnt <= 1) cout << -1 << endl;
	else
	{
		vector<ll> vec, prime;
		vec.push_back(cnt);
		for(ll j=2; j*j<=cnt; j++)
		{
			if(cnt%j == 0)
			{
				vec.push_back(j);
				vec.push_back(cnt/j);
			}
		}
		for(ll i : vec)
		{
			int f = 0;
			for(ll j : prime) if(i%j == 0) f = 1;
			if(!f) prime.push_back(i);
		}
		ll ans = 1e18;
		//cout << sol(3) << endl;
		for(ll i : prime) ans = min(ans, sol(i));
		cout << ans << endl;
	}
}


import java.util.Scanner;

public class vanyaandFence {

	public static void main(String[] args) {
      int s=0,l=0,n;
     String str;

        Scanner sc = new Scanner(System.in);
         n=sc.nextInt();

		     str= sc.next();
		     for (int i = 0; i <n; i++) {
				if(str.charAt(i)!='.')
					{s=i;
					break;
					}
			}
		  for (int i = s; i <n; i++) {
				if(str.charAt(i)=='.')
					{
					l=i;
					break;
					}

		}

        if(str.charAt(s)=='R'&&str.charAt(l-1)=='R')
        {
        	System.out.println(s+1+" "+(l+1));
        }
        else if(str.charAt(s)=='L'&&str.charAt(l-1)=='L')
        {
        	System.out.println(l+" "+s);
        }
        else if(str.charAt(s)=='R'&&str.charAt(l-1)=='L')
        {
        	s=l-s-1;
        	 l=str.indexOf('L')+1;

        	System.out.println(s+" "+l);
        }
        //System.out.println(s+"  "+l);
			sc.close();
	}

}


import java.util.Scanner;

public class vanyaandFence {

	public static void main(String[] args) {
      int s=0,l=0,n;
     String str;

        Scanner sc = new Scanner(System.in);
         n=sc.nextInt();

		     str= sc.next();
		     for (int i = 0; i <n; i++) {
		    	 if(str.charAt(i)!='.')
		    	 {
		    		 if(str.charAt(i)=='R')
		    		 {
		    			 while(str.charAt(i)=='R') i++;

		    		        System.out.println(i+" "+(i+1));

		    		 }
		    		 else
		    		 {
		    		        System.out.println(i+1+" "+i);

		    		 }
		    		 break;
		    	 }

		     }
        //System.out.println(s+"  "+l);
			sc.close();
	}

}


import java.util.Scanner;

public class vanyaandFence {

	public static void main(String[] args) {
      int s=0,l=0,n;
     String str;

        Scanner sc = new Scanner(System.in);
         n=sc.nextInt();

		     str= sc.next();
		     for (int i = 0; i <n; i++) {
				if(str.charAt(i)!='.')
					{s=i;
					break;
					}
			}
		  for (int i = s; i <n; i++) {
				if(str.charAt(i)=='.')
					{
					l=i;
					break;
					}

		}

        if(str.charAt(s)=='R'&&str.charAt(l-1)=='R')
        {
        	System.out.println(s+1+" "+(l));
        }
        else if(str.charAt(s)=='L'&&str.charAt(l-1)=='L')
        {
        	System.out.println(l+" "+s);
        }
        else if(str.charAt(s)=='R'&&str.charAt(l-1)=='L')
        {
        	s=l-s-1;
        	 l=str.indexOf('L')+1;

        	System.out.println(s+" "+l);
        }
        //System.out.println(s+"  "+l);
			sc.close();
	}

}


import java.util.Scanner;

public class vanyaandFence {

	public static void main(String[] args) {
      int s=0,l=0,n;
     String str;

        Scanner sc = new Scanner(System.in);
         n=sc.nextInt();

		     str= sc.next();
		     for (int i = 0; i <n; i++) {
		    	 if(str.charAt(i)!='.')
		    	 {
		    		 if(str.charAt(i)=='R')
		    		 {
		    			 while(str.charAt(i)=='R') i++;

		    		        System.out.println(i+"  "+i+1);

		    		 }
		    		 else
		    		 {
		    		        System.out.println(i+1+"  "+i);

		    		 }
		    	 }

		     }
        //System.out.println(s+"  "+l);
			sc.close();
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class CodeForces {
    public static void main(String[] args) throws IOException {
        reader input = new reader();
        int n = input.nextInt();
        char array[]=new char[n];
        String s=input.next();
        int R=s.indexOf('R');
        int L=s.indexOf('L');
        if(R!=-1&&L!=-1){
            System.out.println(R+1+" "+L);
        }
        if(R==-1){
            int Llast=s.lastIndexOf('L');
            if(Llast!=L)
                System.out.println((Llast+1)+" "+(L+1));
            else
                System.out.println(Llast+" "+(L+1));
        }
        if(L==-1){
            int Rlast=s.lastIndexOf('R');
            if(Rlast!=R)
                System.out.println((R+1)+" "+(Rlast+1));
            else
                System.out.println((R+1)+" "+(Rlast+2));
        }
    }
}

class reader {
    BufferedReader br;
    StringTokenizer st;

    public reader()
    {
        br = new BufferedReader(new
                InputStreamReader(System.in));
    }
    String next()
    {
        while (st == null || !st.hasMoreElements())
        {
            try
            {
                st = new StringTokenizer(br.readLine());
            }
            catch (IOException  e)
            {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }
    int nextInt()
    {
        return Integer.parseInt(next());
    }
    long nextLong()
    {
        return Long.parseLong(next());
    }
    double nextDouble()
    {
        return Double.parseDouble(next());
    }
    String nextLine()
    {
        String str = "";
        try
        {
            str = br.readLine();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return str;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class CodeForces {
    public static void main(String[] args) throws IOException {
        reader input = new reader();
        int n = input.nextInt();
        char array[]=new char[n];
        String s=input.next();
        int R=s.indexOf('R');
        int L=s.indexOf('L');
        if(R!=-1&&L!=-1){
            System.out.println(R+1+" "+L);
        }
        if(R==-1){
            int Llast=s.lastIndexOf('L');
            System.out.println((Llast+1)+" "+(L));
        }
        if(L==-1){
            int Rlast=s.lastIndexOf('R');
            System.out.println((R+1)+" "+(Rlast+2));
        }
    }
}

class reader {
    BufferedReader br;
    StringTokenizer st;

    public reader()
    {
        br = new BufferedReader(new
                InputStreamReader(System.in));
    }
    String next()
    {
        while (st == null || !st.hasMoreElements())
        {
            try
            {
                st = new StringTokenizer(br.readLine());
            }
            catch (IOException  e)
            {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }
    int nextInt()
    {
        return Integer.parseInt(next());
    }
    long nextLong()
    {
        return Long.parseLong(next());
    }
    double nextDouble()
    {
        return Double.parseDouble(next());
    }
    String nextLine()
    {
        String str = "";
        try
        {
            str = br.readLine();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return str;
    }
}


    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.*;
    /**
     *
     * @author abdelmagied
     */
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    import javafx.scene.Node;

    /**
     *
     * @author abdelmagied
     */
    public class JavaApplication1 {
        /**
         * @param args the command line arguments
       */
       public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();

            String str = sc.next();
            int start = 0 , last = 0;

            for(int i = 0 ; i < str.length() ; i++){
                 if(str.charAt(i) != '.'){
                     start = i;
                     break;
                 }
            }

            for(int i = str.length() - 1 ; i>= 0 ; i--){
                  if(str.charAt(i) != '.'){
                      last = i;
                      break;
                  }
            }

            if(str.charAt(start) == 'L' && str.charAt(last) == 'L'){
                System.out.println(last+1 + " " + start);
            }

           else if(str.charAt(start) == 'R' && str.charAt(last) == 'R'){
                System.out.println(start+1 +" "+last+2);
            }
           else{
               for(int i = last ; i >= start ; i--){
                   if(str.charAt(i) == 'R'){
                       last = i;
                       break;
                   }
               }

               System.out.println((start+1) + " "+ (last+1));
           }

       }
}


    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.*;
    /**
     *
     * @author abdelmagied
     */
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    import javafx.scene.Node;

    /**
     *
     * @author abdelmagied
     */
    public class JavaApplication1 {
        /**
         * @param args the command line arguments
       */
       public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();

            String str = sc.next();
            int start = 0 , last = 0;

            for(int i = 0 ; i < str.length() ; i++){
                 if(str.charAt(i) != '.'){
                     start = i;
                     break;
                 }
            }

            for(int i = str.length() - 1 ; i>= 0 ; i--){
                  if(str.charAt(i) != '.'){
                      last = i;
                      break;
                  }
            }

            if(str.charAt(start) == 'L' && str.charAt(last) == 'L'){
                System.out.println(last+1 + " " + start);
            }

           else if(str.charAt(start) == 'R' && str.charAt(last) == 'R'){
                System.out.println(start+1 +" "+last+2);
            }
           else{
               for(int i = last ; i >= start ; i--){
                   if(str.charAt(i) == 'L'){
                       last = i;
                       break;
                   }
               }

               System.out.println(start+1 + " "+ last);
           }

       }
}


    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.*;
    /**
     *
     * @author abdelmagied
     */
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    import javafx.scene.Node;

    /**
     *
     * @author abdelmagied
     */
    public class JavaApplication1 {
        /**
         * @param args the command line arguments
       */
       public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();

            String str = sc.next();
            int start = 0 , last = 0;

            for(int i = 0 ; i < str.length() ; i++){
                 if(str.charAt(i) != '.'){
                     start = i;
                     break;
                 }
            }

            for(int i = str.length() - 1 ; i>= 0 ; i--){
                  if(str.charAt(i) != '.'){
                      last = i;
                      break;
                  }
            }

            if(str.charAt(start) == 'L' && str.charAt(last) == 'L'){
                System.out.println((last+1) + " " + (start));
            }

           else if(str.charAt(start) == 'R' && str.charAt(last) == 'R'){
                System.out.println((start+1) +" "+(last+2));
            }
           else{
               for(int i = last ; i >= start ; i--){
                   if(str.charAt(i) == 'R'){
                       last = i;
                       break;
                   }
               }

               System.out.println((start+1) + " "+ (last+1));
           }

       }
}


    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.*;
    /**
     *
     * @author abdelmagied
     */
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    import javafx.scene.Node;

    /**
     *
     * @author abdelmagied
     */
    public class JavaApplication1 {
        /**
         * @param args the command line arguments
       */
       public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();

            String str = sc.next();
            int leftMoves = 0 , rightMoves = 0;
            boolean right = false , left = false;
            for(int i = 0 ; i < str.length() ; i++){
                  if(str.charAt(i) == 'L'){
                      if(right == true){
                          break;
                      }
                      leftMoves++;
                      break;
                  }else if(str.charAt(i) == 'R'){
                      rightMoves++;
                      right = true;
                  }
            }

            int start = (leftMoves > 0)? 1 : n - rightMoves;
            int end = start;

            for(int i = 0 ; i < str.length() ; i++){
                if(str.charAt(i) == 'L'){
                    end--;
                }else if(str.charAt(i) == 'R'){
                    end++;
                }
            }
            System.out.println(start + " " + end);
       }
}


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class SnowFootprints implements Closeable {

    private InputReader in = new InputReader(System.in);
    private PrintWriter out = new PrintWriter(System.out);

    public void solve() {
        int n = in.ni();
        char[] x = in.next().toCharArray();
        int firstRight = -1, lastRight = -1;
        int firstLeft = -1, lastLeft = -1;
        for (int i = 0; i < n; i++) {
            if (x[i] == 'R') {
                if (firstRight == -1) firstRight = i + 1;
                else lastRight = i + 1;
            }
        }
        for (int i = 0; i < n; i++) {
            if (x[i] == 'L') {
                if (firstLeft == -1) firstLeft = i + 1;
                else lastLeft = i + 1;
            }
        }
        if (firstRight != -1) {
            out.println(firstRight + " " + ((lastRight == - 1) ? firstRight + 1 : lastRight));
        } else {
            out.println(firstLeft + " " + ((lastLeft == -1) ? firstLeft - 1 : lastLeft));
        }
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ni() {
            return Integer.parseInt(next());
        }

        public long nl() {
            return Long.parseLong(next());
        }

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (SnowFootprints instance = new SnowFootprints()) {
            instance.solve();
        }
    }
}


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class SnowFootprints implements Closeable {

    private InputReader in = new InputReader(System.in);
    private PrintWriter out = new PrintWriter(System.out);

    public void solve() {
        int n = in.ni();
        char[] x = in.next().toCharArray();
        int firstRight = -1, lastRight = -1;
        int firstLeft = -1, lastLeft = -1;
        for (int i = 0; i < n; i++) {
            if (x[i] == 'R') {
                if (firstRight == -1) firstRight = i + 1;
                else lastRight = i + 1;
            }
        }
        for (int i = 0; i < n; i++) {
            if (x[i] == 'L') {
                if (firstLeft == -1) firstLeft = i + 1;
                else lastLeft = i + 1;
            }
        }
        if (firstRight != -1) {
            out.println(firstRight + " " + ((lastRight == - 1) ? firstRight + 1 : lastRight + 1));
        } else {
            out.println(firstLeft + " " + ((lastLeft == -1) ? firstLeft - 1 : lastLeft - 1));
        }
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ni() {
            return Integer.parseInt(next());
        }

        public long nl() {
            return Long.parseLong(next());
        }

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (SnowFootprints instance = new SnowFootprints()) {
            instance.solve();
        }
    }
}


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class SnowFootprints implements Closeable {

    private InputReader in = new InputReader(System.in);
    private PrintWriter out = new PrintWriter(System.out);

    public void solve() {
        int n = in.ni();
        char[] x = in.next().toCharArray();
        int firstRight = -1, lastRight = -1;
        int firstLeft = -1, lastLeft = -1;
        for (int i = 0; i < n; i++) {
            if (x[i] == 'R') {
                if (firstRight == -1) firstRight = i + 1;
                else lastRight = i + 1;
            }
        }
        for (int i = 0; i < n; i++) {
            if (x[i] == 'L') {
                if (firstLeft == -1) firstLeft = i + 1;
                else lastLeft = i + 1;
            }
        }
        if (firstRight != -1) {
            out.println(firstRight + " " + ((lastRight == - 1) ? firstRight + 1 : lastRight + 1));
        } else {
            out.println(((lastLeft == -1) ? firstLeft: lastLeft) + " " + (firstLeft - 1));
        }
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ni() {
            return Integer.parseInt(next());
        }

        public long nl() {
            return Long.parseLong(next());
        }

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (SnowFootprints instance = new SnowFootprints()) {
            instance.solve();
        }
    }
}


import java.util.*;
import java.io.*;
public class SnowFootprints
{

	/************************ SOLUTION STARTS HERE ************************/

	//DONT FORGET TO COMMIT AND PUSH TO GITHUB

	private static void solve(FastScanner s1, FastWriter out){
		int n = s1.nextInt();
		String in = s1.nextLine();
		int l1 = in.indexOf('R');
		int r1 = in.lastIndexOf('R');
		int l2 = in.indexOf('L');
		int r2 = in.lastIndexOf('L');
		if(l1 == -1)
		{
			out.print((r2+1)+" "+(l2));
		}
		else if(l2 == -1)
			out.print((l1+1)+" "+(r1+2));
		else
			out.print((l1+1)+" "+(r1+1));
	}

	/************************ SOLUTION ENDS HERE ************************/

	/************************ TEMPLATE STARTS HERE ************************/

	public static void main(String []args) throws IOException {
		FastScanner in  = new FastScanner(System.in);
		FastWriter  out = new FastWriter(System.out);
		solve(in, out);
		in.close();
		out.close();
	}

	static class FastScanner{
		public BufferedReader reader;
		public StringTokenizer st;
		public FastScanner(InputStream stream){
			reader = new BufferedReader(new InputStreamReader(stream));
			st = null;
		}
		public String next(){
			while(st == null || !st.hasMoreTokens()){
				try{
					String line = reader.readLine();
					if(line == null) return null;
					st = new StringTokenizer(line);
				}catch (Exception e){
					throw (new RuntimeException());
				}
			}
			return st.nextToken();
		}
		public String nextLine(){
			String str = null;
			try {
				str = reader.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
		public int nextInt(){
			return Integer.parseInt(next());
		}
		public long nextLong(){
			return Long.parseLong(next());
		}
		public double nextDouble(){
			return Double.parseDouble(next());
		}
		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}
		public void close(){
			try{ reader.close(); } catch(IOException e){e.printStackTrace();}
		}
	}
	static class FastWriter{
		BufferedWriter writer;
		public FastWriter(OutputStream stream){
			writer = new BufferedWriter(new OutputStreamWriter(stream));
		}
		public void print(int i) {
			print(Integer.toString(i));
		}
		public void println(int i) {
			print(Integer.toString(i));
			print('\n');
		}
		public void print(long i) {
			print(Long.toString(i));
		}
		public void println(long i) {
			print(Long.toString(i));
			print('\n');
		}
		public void print(double i) {
			print(Double.toString(i));
		}
		public void print(boolean i) {
			print(Boolean.toString(i));
		}
		public void print(Object o){
			print(o.toString());
		}
		public void println(Object o){
			print(o.toString());
			print('\n');
		}
		public void print(char i) {
			try{writer.write(i);} catch(IOException e){e.printStackTrace();}
		}
		public void print(String s){
			try{writer.write(s);} catch(IOException e){e.printStackTrace();}
		}
		public void println(String s){
			try{writer.write(s);writer.write('\n');} catch(IOException e){e.printStackTrace();}
		}
		public void println(){
			try{writer.write('\n');} catch(IOException e){e.printStackTrace();}
		}
		public void print(int arr[])
		{
			for (int i = 0; i < arr.length; i++) {
				print(arr[i]);
				print(' ');
			}
		}
		public void close(){
			try{writer.close();} catch(IOException e){e.printStackTrace();}
		}
	}

	/************************ TEMPLATE ENDS HERE ************************/
}


import java.util.*;
import java.io.*;
public class SnowFootprints
{

	/************************ SOLUTION STARTS HERE ************************/

	//DONT FORGET TO COMMIT AND PUSH TO GITHUB

	private static void solve(FastScanner s1, FastWriter out){

		String in = s1.nextLine();
		int l1 = in.indexOf('R');
		int r1 = in.lastIndexOf('R');
		int l2 = in.indexOf('L');
		int r2 = in.lastIndexOf('L');
		if(l1 == -1)
		{
			out.print((r2+1)+" "+(l2+1));
		}
		else
			out.print((l1+1)+" "+(r1+1));
	}

	/************************ SOLUTION ENDS HERE ************************/

	/************************ TEMPLATE STARTS HERE ************************/

	public static void main(String []args) throws IOException {
		FastScanner in  = new FastScanner(System.in);
		FastWriter  out = new FastWriter(System.out);
		solve(in, out);
		in.close();
		out.close();
	}

	static class FastScanner{
		public BufferedReader reader;
		public StringTokenizer st;
		public FastScanner(InputStream stream){
			reader = new BufferedReader(new InputStreamReader(stream));
			st = null;
		}
		public String next(){
			while(st == null || !st.hasMoreTokens()){
				try{
					String line = reader.readLine();
					if(line == null) return null;
					st = new StringTokenizer(line);
				}catch (Exception e){
					throw (new RuntimeException());
				}
			}
			return st.nextToken();
		}
		public String nextLine(){
			String str = null;
			try {
				str = reader.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
		public int nextInt(){
			return Integer.parseInt(next());
		}
		public long nextLong(){
			return Long.parseLong(next());
		}
		public double nextDouble(){
			return Double.parseDouble(next());
		}
		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}
		public void close(){
			try{ reader.close(); } catch(IOException e){e.printStackTrace();}
		}
	}
	static class FastWriter{
		BufferedWriter writer;
		public FastWriter(OutputStream stream){
			writer = new BufferedWriter(new OutputStreamWriter(stream));
		}
		public void print(int i) {
			print(Integer.toString(i));
		}
		public void println(int i) {
			print(Integer.toString(i));
			print('\n');
		}
		public void print(long i) {
			print(Long.toString(i));
		}
		public void println(long i) {
			print(Long.toString(i));
			print('\n');
		}
		public void print(double i) {
			print(Double.toString(i));
		}
		public void print(boolean i) {
			print(Boolean.toString(i));
		}
		public void print(Object o){
			print(o.toString());
		}
		public void println(Object o){
			print(o.toString());
			print('\n');
		}
		public void print(char i) {
			try{writer.write(i);} catch(IOException e){e.printStackTrace();}
		}
		public void print(String s){
			try{writer.write(s);} catch(IOException e){e.printStackTrace();}
		}
		public void println(String s){
			try{writer.write(s);writer.write('\n');} catch(IOException e){e.printStackTrace();}
		}
		public void println(){
			try{writer.write('\n');} catch(IOException e){e.printStackTrace();}
		}
		public void print(int arr[])
		{
			for (int i = 0; i < arr.length; i++) {
				print(arr[i]);
				print(' ');
			}
		}
		public void close(){
			try{writer.close();} catch(IOException e){e.printStackTrace();}
		}
	}

	/************************ TEMPLATE ENDS HERE ************************/
}


import java.util.*;
import java.io.*;
public class SnowFootprints
{

	/************************ SOLUTION STARTS HERE ************************/

	//DONT FORGET TO COMMIT AND PUSH TO GITHUB

	private static void solve(FastScanner s1, FastWriter out){
		int n = s1.nextInt();
		String in = s1.nextLine();
		int l1 = in.indexOf('R');
		int r1 = in.lastIndexOf('R');
		int l2 = in.indexOf('L');
		int r2 = in.lastIndexOf('L');
		if(l1 == -1)
		{
			out.print((r2+1)+" "+(l2+1));
		}
		else
			out.print((l1+1)+" "+(r1+1));
	}

	/************************ SOLUTION ENDS HERE ************************/

	/************************ TEMPLATE STARTS HERE ************************/

	public static void main(String []args) throws IOException {
		FastScanner in  = new FastScanner(System.in);
		FastWriter  out = new FastWriter(System.out);
		solve(in, out);
		in.close();
		out.close();
	}

	static class FastScanner{
		public BufferedReader reader;
		public StringTokenizer st;
		public FastScanner(InputStream stream){
			reader = new BufferedReader(new InputStreamReader(stream));
			st = null;
		}
		public String next(){
			while(st == null || !st.hasMoreTokens()){
				try{
					String line = reader.readLine();
					if(line == null) return null;
					st = new StringTokenizer(line);
				}catch (Exception e){
					throw (new RuntimeException());
				}
			}
			return st.nextToken();
		}
		public String nextLine(){
			String str = null;
			try {
				str = reader.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
		public int nextInt(){
			return Integer.parseInt(next());
		}
		public long nextLong(){
			return Long.parseLong(next());
		}
		public double nextDouble(){
			return Double.parseDouble(next());
		}
		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}
		public void close(){
			try{ reader.close(); } catch(IOException e){e.printStackTrace();}
		}
	}
	static class FastWriter{
		BufferedWriter writer;
		public FastWriter(OutputStream stream){
			writer = new BufferedWriter(new OutputStreamWriter(stream));
		}
		public void print(int i) {
			print(Integer.toString(i));
		}
		public void println(int i) {
			print(Integer.toString(i));
			print('\n');
		}
		public void print(long i) {
			print(Long.toString(i));
		}
		public void println(long i) {
			print(Long.toString(i));
			print('\n');
		}
		public void print(double i) {
			print(Double.toString(i));
		}
		public void print(boolean i) {
			print(Boolean.toString(i));
		}
		public void print(Object o){
			print(o.toString());
		}
		public void println(Object o){
			print(o.toString());
			print('\n');
		}
		public void print(char i) {
			try{writer.write(i);} catch(IOException e){e.printStackTrace();}
		}
		public void print(String s){
			try{writer.write(s);} catch(IOException e){e.printStackTrace();}
		}
		public void println(String s){
			try{writer.write(s);writer.write('\n');} catch(IOException e){e.printStackTrace();}
		}
		public void println(){
			try{writer.write('\n');} catch(IOException e){e.printStackTrace();}
		}
		public void print(int arr[])
		{
			for (int i = 0; i < arr.length; i++) {
				print(arr[i]);
				print(' ');
			}
		}
		public void close(){
			try{writer.close();} catch(IOException e){e.printStackTrace();}
		}
	}

	/************************ TEMPLATE ENDS HERE ************************/
}