#include using namespace std; using ll = long long; const int inf = 1 << 30; const ll INF = 1LL << 60; const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1}; #define rep(i, s, t) for (ll i = (ll)s; i < (ll)(t); i++) #define rrep(i, s, t) for (ll i = (ll)(t) - 1; i >= (ll)(s); i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmin(T1& x, T2 y) { return x > y ? (x = y, true) : false; } template bool chmax(T1& x, T2 y) { return x < y ? (x = y, true) : false; } template using min_heap = priority_queue, greater>; template using max_heap = priority_queue; void solve() { int N; cin >> N; string S; cin >> S; reverse(all(S)); ll A; cin >> A; vector two(N); two[0] = 1; rep(i, 1, N) two[i] = (2 * two[i - 1]) % A; map mp; ll z = -1; rep(bit, 0, 1 << (N / 2)) { int cnt = 0; ll md = 0; bool is_zero = true; rep(i, 0, N / 2) { if (bit >> i & 1) { cnt++; if (S[i] == '0') { md = (md + two[i]) % A; is_zero = false; } } else { if (S[i] == '1') { md = (md + two[i]) % A; is_zero = false; } } } if (is_zero) z = cnt; else { if (!mp.count(md)) mp[md] = cnt; else chmin(mp[md], cnt); } } int ans = inf; rep(bit, 0, 1 << ((N + 1) / 2)) { int cnt = 0; ll md = 0; bool is_zero = true; rep(i, 0, (N + 1) / 2) { if (bit >> i & 1) { cnt++; if (S[N / 2 + i] == '0') { md = (md + two[N / 2 + i]) % A; is_zero = false; } } else { if (S[N / 2 + i] == '1') { md = (md + two[N / 2 + i]) % A; is_zero = false; } } } ll val = (A - md) % A; if (is_zero) { if (mp.count(0)) chmin(ans, cnt + mp[0]); } else { if (mp.count(val)) chmin(ans, cnt + mp[val]); if (val == 0) chmin(ans, cnt + z); } } if (ans == inf) cout << -1 << "\n"; else cout << ans << "\n"; } int main() { cin.tie(0)->sync_with_stdio(0); cout << fixed << setprecision(15); srand(time(NULL)); int T; // cin >> T; T = 1; while (T--) solve(); }