Problem:
Problem F:
Find the Multiples
You are given a sequence
a
0
a
1
...
a
N
-1
digits and a prime number
Q
. For each
i
≤
j
with
a
i
≠ 0, the subsequence
a
i
a
i
+1
...
a
j
can be read as a decimal representation of a positive integer. Subsequences with leading zeros are not considered. Your task is to count the number of pairs (
i
,
j
) such that the corresponding subsequence is a multiple of
Q
.
Input
The input consists of at most 50 datasets. Each dataset is represented by a line containing four integers
N
,
S
,
W
, and
Q
, separated by spaces, where 1 ≤
N
≤ 10
5
, 1 ≤
S
≤ 10
9
, 1 ≤
W
≤ 10
9
, and
Q
is a prime number less than 10
8
. The sequence
a
0
...
a
N
-1
of length
N
is generated by the following code, in which ai is written as
a[i]
.
int g = S;
    for(int i=0; i<N; i++) {
        a[i] = (g/7) % 10;
        if( g%2 == 0 ) { g = (g/2); }
        else           { g = (g/2) ^ W; }
    }
Note:
the operators
/
,
%
, and
^
are the integer division, the modulo, and the bitwise exclusiveor, respectively. The above code is meant to be a random number generator. The intended solution does not rely on the way how the sequence is generated.
The end of the input is indicated by a line containing four zeros separated by spaces.
Output
For each dataset, output the answer in a line. You may assume that the answer is less than 2
30
.
Sample Input
3 32 64 7
4 35 89 5
5 555 442 3
5 777 465 11
100000 666 701622763 65537
0 0 0 0
Output for the Sample Input
2
4
6
3
68530
In the first dataset, the sequence is 421. We can find two multiples of
Q
= 7, namely, 42 and 21.
In the second dataset, the sequence is 5052, from which we can find 5, 50, 505, and 5 being the multiples of
Q
= 5. Notice that we don't count 0 or 05 since they are not a valid representation of positive integers. Also notice that we count 5 twice, because it occurs twice in different positions.
In the third and fourth datasets, the sequences are 95073 and 12221, respectively.

Submitted solutions:

code_snippet: #include <cstdio>
#include <map>
#include <iostream>
#include <cstring>
using namespace std;
using std::map;
int a[100010];
map<long long,int> mp;
long long pow_mod(long long a,long long b,long long p)
{
	long long ans = 1;
	while(b) {
		if(b&1) ans = ans * a % p;
		b >>= 1; a = a * a % p;
	}
	return  ans;
}

int main()
{
	long long N,S,W,Q;
	while(std::cin>>N>>S>>W>>Q)
	{
		if(!N) break;
		mp.clear();
		int g = S;
		a[0] = 0;
		for(int i = 1; i <= N; i++)
		{
			a[i] = (g/7) % 10;
			if(g%2==0) g /= 2;
			else g = (g/2) ^ W;
		}
		if(Q == 5 || Q == 2)
		{
			int ans = 0;
			int cnt = 0;
			for(int i = 1;i <= N;i++)
			{
				if(a[i] != 0)cnt++;
				if(a[i] % Q == 0)ans += cnt;
			}
			printf("%d\n",ans);
			continue;
		}
		long long ans = 0;
		long long sum = 0;
		long long S = 1;
		for(int i = N; i >= 1; i--)
		{
			sum = (S*a[i] + sum) % Q;
	        if(a[i] > 0 && !sum) ans++;
			if(a[i] > 0) ans +=  mp[sum] ;
			mp[sum]++;
			S *= 10;
			S %= Q;
		}
		std::cout<<ans<<std::endl;
	}
	return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 9440
final_rank: 14

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
while(1) {
    ll N, S, W, Q;
    cin >> N >> S >> W >> Q;
    if (N == 0) return 0;
    ll G = S;
    vector<ll> A(N);
    rep(i,0,N) {
        A[i] = (G/7) % 10;
        if (G % 2 == 0) G /= 2;
        else G = (G/2) ^ W;
    }
    reverse(ALL(A));
    if (Q == 2) {
        ll ANS = 0;
        ll COUNT = 0;
        rep(i,0,N) {
            if (A[i] % 2 == 0) COUNT++;
            if (A[i] != 0) ANS += COUNT;
        }
        cout << ANS << endl;
        continue;
    }
    if (Q == 5) {
        ll ANS = 0;
        ll COUNT = 0;
        rep(i,0,N) {
            if (A[i] % 5 == 0) COUNT++;
            if (A[i] != 0) ANS += COUNT;
        }
        cout << ANS << endl;
        continue;
    }
    ll D = 1, Cur = 0;
    ll ANS = 0;
    map<ll,int> mp;
    mp[0]++;
    rep(i,0,N) {
        Cur += (D * A[i]);
        D *= 10;
        Cur %= Q;
        D %= Q;
        if (A[i] != 0) ANS += mp[Cur];
        mp[Cur]++;
    }
    cout << ANS << endl;
}
}
accuracy: 1
time_ms: 380
memory_kb: 9848
final_rank: 12

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int solve2(int N, vector<i64> a, int Q) {
    int ans = 0, zero = 0;
    for(int i : rep(N)) {
        if(a[i] % Q == 0) ans += i + 1 - zero;
        if(a[i] == 0) zero++;
    }
    return ans - zero;
}

int solve(int N, int S, int W, int Q) {
    vector<i64> a(N);
    {
        int g = S;
        for(int i = 0; i < N; i++) {
            a[i] = (g / 7) % 10;
            if(g % 2 == 0) { g = (g / 2); }
            else {g = (g / 2) ^ W; }
        }
    }

    if(Q == 2 or Q == 5) return solve2(N, a, Q);

    i64 pow10 = 1;
    vector<i64> b(N);
    for(int i : revrep(N)) {
        b[i] = (a[i] * pow10) % Q;
        pow10 = (pow10 * 10) % Q;
    }

    vector<i64> s(N + 1, 0);
    for(int i : revrep(N)) s[i] = (s[i + 1] + b[i]) % Q;
    int ans = 0;
    map<i64, int> mp;
    mp[0] = 1;
    for(int i : revrep(N)) {
        if(a[i] != 0) ans += mp[s[i]];
        mp[s[i]]++;
    }
    return ans;
}

int main() {
    while(true) {
        int N = in(), S = in(), W = in(), Q = in();
        if(make_tuple(N, S, W, Q) == make_tuple(0, 0, 0, 0)) return 0;
        print(solve(N, S, W, Q));
    }
}
accuracy: 1
time_ms: 410
memory_kb: 10956
final_rank: 20

code_snippet: #include<bits/stdc++.h>

using namespace std;

#define rep(i, n) for(int i = 0; i < (n); i++)
#define per(i, n) for(int i = (n)-1; i >= 0; i--)
#define rep2(i, l, r) for(int i = (l); i < (r); i++)
#define per2(i, l, r) for(int i = (r)-1; i >= (l); i--)
#define each(e, x) for(auto &e : x)
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define eb emplace_back
#define MM << ' ' <<
#define TT template<typename T>
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

TT bool chmin(T &x, T y) { return x > y ? (x = y, true) : false; }

TT bool chmax(T &x, T y) { return x < y ? (x = y, true) : false; }

TT using minheap = priority_queue<T, vector<T>, greater<T>>;
TT using maxheap = priority_queue<T>;

TT void print(vector<T> v, T x = 0) {
    int n = sz(v);
    rep(i, n) cout << v[i] + x << (i == n - 1 ? '\n' : ' ');
    if (n == 0) cout << '\n';
}

TT void printn(vector<T> v, T x = 0) {
    int n = sz(v);
    rep(i, n) cout << v[i] + x << '\n';
}

TT void rearrange(vector<T> &v) {
    sort(all(v));
    v.erase(unique(all(v)), end(v));
}

TT int lb(vector<T> &v, T x) { return lower_bound(all(v), x) - begin(v); }

TT int ub(vector<T> &v, T x) { return upper_bound(all(v), x) - begin(v); }

const int inf = (1 << 30) - 1;
const ll INF = (1LL << 60) - 1;

struct io_setup {
    io_setup() {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout << fixed << setprecision(15);
    }
} io_setup;

int main() {
    while (1) {
        int n, s, w, p;
        cin >> n >> s >> w >> p;
        if  (!n)
            break;
        vector<int> a(n);
        int g = s;
        rep(i, n) {
            a[i] = g / 7 % 10;
            g = (g % 2 == 0 ? g / 2 : (g / 2) ^ w);
        }
        ll ans = 0;
        if (p == 2 || p == 5) {
            ll cnt = 0;
            rep(i, n) {
                if (a[i] % p == 0) {
                    if (a[i]) ans++;
                    ans += cnt;
                }
                if (a[i]) cnt++;
            }
        }
        else {
            map<ll, ll> m;
            ll val = 0, t = 1;
            m[0]++;
            per(i, n) {
                val += t * a[i];
                val %= p;
                if (a[i]) ans += m[val];
                m[val]++;
                t *= 10, t %= p;
            }
        }
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 400
memory_kb: 9400
final_rank: 16

code_snippet: /**
 *    author:  otera
**/
#include<bits/stdc++.h>
using namespace std;

// #define int long long

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using int128_t = __int128_t;
#define repa(i, n) for(int i = 0; i < n; ++ i)
#define repb(i, a, b) for(int i = a; i < b; ++ i)
#define repc(i, a, b, c) for(int i = a; i < b; i += c)
#define overload4(a, b, c, d, e, ...) e
#define overload3(a, b, c, d, ...) d
#define rep(...) overload4(__VA_ARGS__, repc, repb, repa)(__VA_ARGS__)
#define rep1a(i, n) for(int i = 0; i <= n; ++ i)
#define rep1b(i, a, b) for(int i = a; i <= b; ++ i)
#define rep1c(i, a, b, c) for(int i = a; i <= b; i += c)
#define rep1(...) overload4(__VA_ARGS__, rep1c, rep1b, rep1a)(__VA_ARGS__)
#define rev_repa(i, n) for(int i=n-1;i>=0;i--)
#define rev_repb(i, a, b) assert(a > b);for(int i=a;i>b;i--)
#define rev_rep(...) overload3(__VA_ARGS__, rev_repb, rev_repa)(__VA_ARGS__)
#define rev_rep1a(i, n) for(int i=n;i>=1;i--)
#define rev_rep1b(i, a, b) assert(a >= b);for(int i=a;i>=b;i--)
#define rev_rep1(...) overload3(__VA_ARGS__, rev_rep1b, rev_rep1a)(__VA_ARGS__)
typedef pair<int, int> P;
typedef pair<ll, ll> LP;
#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define eb emplace_back
#define fr first
#define sc second
#define all(c) c.begin(),c.end()
#define rall(c) c.rbegin(), c.rend()
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define Sort(a) sort(all(a))
#define Rev(a) reverse(all(a))
#define Uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define si(c) (int)(c).size()
inline ll popcnt(ull a){ return __builtin_popcountll(a); }
#define kth_bit(x, k) ((x>>k)&1)
#define unless(A) if(!(A))
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll intpow(ll a, ll b, ll m) {ll ans = 1; while(b){ if(b & 1) (ans *= a) %= m; (a *= a) %= m; b /= 2; } return ans; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;in(__VA_ARGS__)
#define vec(type,name,...) vector<type>name(__VA_ARGS__)
#define VEC(type,name,size) vector<type>name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>>name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
template <class T> using vc = vector<T>;
template <class T> using vvc = vector<vc<T>>;
template <class T> using vvvc = vector<vvc<T>>;
template <class T> using vvvvc = vector<vvvc<T>>;
template <class T> using pq = priority_queue<T>;
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
template <class T, class U> using umap = unordered_map<T, U>;
template<class T> void scan(T& a){ cin >> a; }
template<class T> void scan(vector<T>& a){ for(auto&& i : a) scan(i); }
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){ scan(head); in(tail...); }
void print(){ cout << ' '; }
template<class T> void print(const T& a){ cout << a; }
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ cout << ' '; print(*i); } }
int out(){ cout << '\n'; return 0; }
template<class T> int out(const T& t){ print(t); cout << '\n'; return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); cout << ' '; out(tail...); return 0; }
#define CHOOSE(a) CHOOSE2 a
#define CHOOSE2(a0,a1,a2,a3,a4,x,...) x
#define debug_1(x1) cout<<#x1<<": "<<x1<<endl
#define debug_2(x1,x2) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<endl
#define debug_3(x1,x2,x3) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<endl
#define debug_4(x1,x2,x3,x4) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<endl
#define debug_5(x1,x2,x3,x4,x5) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<", "#x5<<": "<<x5<<endl
#ifdef DEBUG
#define debug(...) CHOOSE((__VA_ARGS__,debug_5,debug_4,debug_3,debug_2,debug_1,~))(__VA_ARGS__)
#define dump(...) { print(#__VA_ARGS__); print(":"); out(__VA_ARGS__); }
#else
#define debug(...)
#define dump(...)
#endif

struct io_setup {
    io_setup(int precision = 20) {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cout << fixed << setprecision(precision);
    }
} io_setup_ {};

void solve() {
    int n, s, w, q;
    while(cin >> n >> s >> w >> q) {
        if(n == 0) break;
        int g = s;
        vc<int> a(n);
        rep(i, n) {
            a[i] = (g / 7) % 10;
            if(g % 2 == 0) {
                g = g / 2;
            } else {
                g = (g / 2) ^ w;
            }
        }
        if(q == 2 || q == 5) {
            int cnt = 0;
            ll ans = 0;
            rev_rep(i, n) {
                if(a[i] % q == 0) ++ cnt;
                if(a[i] != 0) ans += cnt;
            }
            out(ans);
            continue;
        }
        if(n <= 10) dump(a);
        ll ans = 0;
        map<int, int> mp;
        mp[0] ++;
        int cur = 0;
        int pw = 1;
        for(int i = n - 1; i >= 0; -- i) {
            (cur += a[i] * pw % q) %= q;
            (pw *= 10) %= q;
            if(n <= 10) debug(cur);
            if(a[i] != 0) ans += (ll)mp[cur];
            mp[cur] ++;
        }
        // vc<int> sum(n + 1, 0);
        // sum[n] = n;
        // pw = 1;
        // for(int i = n - 1; i >= 0; -- i) {
        //     sum[i] = sum[i + 1] + a[i] * pw;
        //     sum[i] %= q;
        //     (pw *= 10) %= q;
        // }
        // rep(i, n) {
        //     rep(j, i + 1, n + 1) {
        //         if(a[i] != 0 && sum[i] == sum[j]) ++ ans;
        //     }
        // }
        out(ans);
    } 
}

signed main() {
    int testcase = 1;
    // in(testcase);
    while(testcase--) solve();
    return 0;
}
accuracy: 1
time_ms: 360
memory_kb: 7800
final_rank: 3

code_snippet: #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define _GLIBCXX_DEBUG
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using ll=long long;
using ld=long double;
ll ILL=2167167167167167167;
const int INF=2100000000;
const ll mod=998244353;
#define rep(i,a) for (int i=0;i<a;i++)
#define all(p) p.begin(),p.end()
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> ll LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> ll UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
void yneos(bool a){if(a) cout<<"Yes\n"; else cout<<"No\n";}
template<class T> void vec_out(vector<T> &p){for(int i=0;i<(int)(p.size());i++){if(i) cout<<" ";cout<<p[i];}cout<<"\n";}

int t=INF;
void solve();
// oddloop
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	//cin>>t;
	rep(i,t) solve();
}

void solve(){
	int N,S,W,Q;
	cin>>N>>S>>W>>Q;
	if(N==0){
		t=0;
		return;
	}
	if(Q==2||Q==5){
		ll ans=0,C=0;
		rep(i,N){
			int tmp=(S/7)%10;
			if(tmp%Q==0){
				ans+=C;
				if(tmp!=0) ans++;
			}if(tmp!=0) C++;
			if(S%2==0) S/=2;
			else S=((S/2)^W);
		}
		cout<<ans<<"\n";
		return;
	}
	map<int,int> m;
	ll ans=0;
	ll R=1,A=10,P=Q-2;
	while(P){
		if(P&1){
			R=(R*A)%Q;
		}
		A=(A*A)%Q;
		P>>=1;
	}
	ll v=0,D=1;
	rep(i,N){
		ll tmp=(S/7)%10;
		if(tmp!=0) m[v]++;
		v=(v+tmp*D)%Q;
		D=(R*D)%Q;
		ans+=m[v];
		if(S%2==0) S/=2;
		else S=((S/2)^W);
	}
	cout<<ans<<"\n";
}
accuracy: 1
time_ms: 390
memory_kb: 7568
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    for (int i = 0; i < (int) v.size(); ++i) os << v[i] << " ";
    return os;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    while (true) {
        ll N, S, W, Q;
        cin >> N >> S >> W >> Q;
        if (N == 0) break;

        int g = S;
        vector<ll> a(N);
        rep(i,0,N) {
            a[i] = (g/7) % 10;
            if (g % 2 == 0) g = g / 2;
            else g = (g / 2) ^ W;
        }

        ll ans = 0;
        if (Q == 2 || Q == 5) {
            ll cnt = 0;
            rep(i,0,N) {
                if (a[i] != 0) ++cnt;
                if (a[i] % Q == 0) ans += cnt;
            }
        } else {
            map<ll, ll> cnt;
            cnt[0] = 1;
            reverse(all(a));
            ll x = 0;
            ll p = 1;
            rep(i,0,N) {
                x = (x + a[i]*p) % Q;
                p = p * 10 % Q;
                if (a[i] != 0) ans += cnt[x];
                ++cnt[x];
            }
        }
        cout << ans << "\n";
    }
}
accuracy: 1
time_ms: 370
memory_kb: 9768
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using ll = long long;
#define var auto
const char newl = '\n';

using namespace std;

template<typename T1, typename T2> inline void chmin(T1& a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> inline void chmax(T1& a, T2 b) { if (a < b) a = b; }

bool solve() {
  int n, s, w, q;
  cin >> n >> s >> w >> q;
  if (n == 0) return false;

  vector<int> a(n);
  {
    int g = s;
    for (int i = 0; i < n; i++) {
      a[i] = (g / 7) % 10;
      if (g % 2 == 0) { g = (g / 2); }
      else { g = (g / 2) ^ w; }
    }
  }

  ll res = 0;
  if (q == 2 || q == 5) {
    int tail_cnt = 0;
    for (int i = n - 1; i >= 0; i--) {
      if (a[i] % q == 0) tail_cnt++;
      if (a[i] != 0) res += tail_cnt;
    }
  }
  else {
    map<ll, int> tail_cnts;
    ll cur_mul = 0;
    ll cur_base = 1;
    tail_cnts[cur_mul]++;
    for (int i = n - 1; i >= 0; i--) {
      cur_mul = (a[i] * cur_base + cur_mul) % q;
      if (a[i] != 0) res += tail_cnts[cur_mul];
      tail_cnts[cur_mul]++;
      cur_base = (cur_base * 10) % q;
    }
  }

  cout << res << endl;
  return true;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  while (solve());
}
accuracy: 1
time_ms: 400
memory_kb: 9324
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(A) A.begin(),A.end()
using vll = vector<ll>;
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
struct F {
    ll L;
    ll R;

};
ll d(F f) {
    return f.R - f.L + 1;
}

int main() {
    while (1) {
        ll N, S, W, Q;
        cin >> N >> S >> W >> Q;
        if (N == 0)return 0;

        vll A(N);
        ll g = S;
        for (int i = 0; i < N; i++) {
            A[i] = (g / 7) % 10;
            if (g % 2 == 0) { g = (g / 2); }
            else { g = (g / 2) ^ W; }
        }
        reverse(all(A));
        ll an = 0;
        map<ll, ll> M;
        M[0]++;
        ll k = 0;
        ll t = 1;
        if (Q == 2) {
            vll E(2, 0);
            //E[0]++;
            rep(i, N) {
                E[A[i] % 2]++;
                if (A[i] != 0)an += E[0];
               
            }
            cout << an << endl;
            continue;
        }
        else if (Q == 5) {
            vll E(5, 0);
            //E[0]++;
            rep(i, N) {
                E[A[i] % 5]++;
                if (A[i] != 0)an += E[0];
                
            }
            cout << an << endl;
            continue;
        }
        rep(i, N) {
            k += A[i] * t;
            k %= Q;
            M[k]++;
            t *= 10;
            t %= Q;

            if (A[i] != 0) {
                an += (M[k] - 1);
            }
        }
        cout << an << endl;
    }
}
accuracy: 1
time_ms: 380
memory_kb: 9888
final_rank: 13

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

bool solve() {
    int N, S, W, Q;
    cin >> N >> S >> W >> Q;
    if (N == 0 and S == 0 and W == 0 and W == 0) return false;

    vector<int> a(N);
    int g = S;
    for (int i = 0; i < N; i++) {
        a[i] = (g / 7) % 10;
        if (g % 2 == 0) {
            g = (g / 2);
        } else {
            g = (g / 2) ^ W;
        }
    }

    long long ans = 0;
    if (Q == 2 or Q == 5) {
        int nonzero = 0;
        for (int i = 0; i < N; i++) {
            nonzero += (a[i] != 0);
            if (a[i] % Q == 0) ans += nonzero;
        }
        cout << ans << '\n';
        return true;
    }

    int suf = 0;
    map<int, int> mp;
    mp[suf]++;
    for (int i = N - 1, power = 1; i >= 0; i--, (power *= 10) %= Q) {
        suf = (suf + a[i] * power) % Q;
        if (a[i] != 0) ans += mp[suf];
        mp[suf]++;
    }

    cout << ans << '\n';
    return true;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    while (solve())
        ;
    return 0;
}
accuracy: 1
time_ms: 360
memory_kb: 7756
final_rank: 2

code_snippet: #define LOCAL
#include <bits/stdc++.h>
using namespace std;
#pragma region Macros
typedef long long ll;
typedef __int128_t i128;
typedef unsigned int uint;
typedef unsigned long long ull;
#define ALL(x) (x).begin(), (x).end()

template <typename T> istream& operator>>(istream& is, vector<T>& v) {
    for (T& x : v) is >> x;
    return is;
}
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {
    for (size_t i = 0; i < v.size(); i++) {
        os << v[i] << (i + 1 == v.size() ? "" : " ");
    }
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const pair<T, U>& p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const map<T, U>& m) {
    os << '{';
    for (auto itr = m.begin(); itr != m.end();) {
        os << '(' << itr->first << ',' << itr->second << ')';
        if (++itr != m.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const unordered_map<T, U>& m) {
    os << '{';
    for (auto itr = m.begin(); itr != m.end();) {
        os << '(' << itr->first << ',' << itr->second << ')';
        if (++itr != m.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const set<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const multiset<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const unordered_set<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const deque<T>& v) {
    for (size_t i = 0; i < v.size(); i++) {
        os << v[i] << (i + 1 == v.size() ? "" : " ");
    }
    return os;
}
template <typename T, size_t N> ostream& operator<<(ostream& os, const array<T, N>& v) {
    for (size_t i = 0; i < N; i++) {
        os << v[i] << (i + 1 == N ? "" : " ");
    }
    return os;
}

template <int i, typename T> void print_tuple(ostream&, const T&) {}
template <int i, typename T, typename H, class... Args> void print_tuple(ostream& os, const T& t) {
    if (i) os << ',';
    os << get<i>(t);
    print_tuple<i + 1, T, Args...>(os, t);
}
template <typename... Args> ostream& operator<<(ostream& os, const tuple<Args...>& t) {
    os << '{';
    print_tuple<0, tuple<Args...>, Args...>(os, t);
    return os << '}';
}

void debug_out() { cerr << '\n'; }
template <class Head, class... Tail> void debug_out(Head&& head, Tail&&... tail) {
    cerr << head;
    if (sizeof...(Tail) > 0) cerr << ", ";
    debug_out(move(tail)...);
}
#ifdef LOCAL
#define debug(...)                                                                   \
    cerr << " ";                                                                     \
    cerr << #__VA_ARGS__ << " :[" << __LINE__ << ":" << __FUNCTION__ << "]" << '\n'; \
    cerr << " ";                                                                     \
    debug_out(__VA_ARGS__)
#else
#define debug(...) void(0)
#endif

template <typename T> T gcd(T x, T y) { return y != 0 ? gcd(y, x % y) : x; }
template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; }

int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); }
int topbit(long long t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); }
int botbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); }
int botbit(long long a) { return a == 0 ? 64 : __builtin_ctzll(a); }
int popcount(signed t) { return __builtin_popcount(t); }
int popcount(long long t) { return __builtin_popcountll(t); }
bool ispow2(int i) { return i && (i & -i) == i; }
long long MSK(int n) { return (1LL << n) - 1; }

template <class T> T ceil(T x, T y) {
    assert(y >= 1);
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <class T> T floor(T x, T y) {
    assert(y >= 1);
    return (x > 0 ? x / y : (x - y + 1) / y);
}

template <class T1, class T2> inline bool chmin(T1& a, T2 b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T1, class T2> inline bool chmax(T1& a, T2 b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template <typename T> void mkuni(vector<T>& v) {
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
}
template <typename T> int lwb(const vector<T>& v, const T& x) { return lower_bound(v.begin(), v.end(), x) - v.begin(); }
#pragma endregion

const int INF = 1e9;
const long long IINF = 1e18;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const char dir[4] = {'D', 'R', 'U', 'L'};
const long long MOD = 1000000007;
// const long long MOD = 998244353;

bool solve() {
    int N, S, W, Q;
    cin >> N >> S >> W >> Q;
    if (N == 0 and S == 0 and W == 0 and W == 0) return false;

    vector<int> a(N);
    int g = S;
    for (int i = 0; i < N; i++) {
        a[i] = (g / 7) % 10;
        if (g % 2 == 0) {
            g = (g / 2);
        } else {
            g = (g / 2) ^ W;
        }
    }

    ll ans = 0;
    if (Q == 2 or Q == 5) {
        int nonzero = 0;
        for (int i = 0; i < N; i++) {
            nonzero += (a[i] != 0);
            if (a[i] % Q == 0) ans += nonzero;
        }
        cout << ans << '\n';
        return true;
    }

    int suf = 0;
    map<int, int> mp;
    mp[suf]++;
    for (int i = N - 1, power = 1; i >= 0; i--, (power *= 10) %= Q) {
        suf = (suf + a[i] * power) % Q;
        if (a[i] != 0) ans += mp[suf];
        mp[suf]++;
    }

    cout << ans << '\n';
    return true;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    while (solve())
        ;
    return 0;
}
accuracy: 1
time_ms: 370
memory_kb: 7580
final_rank: 4

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

constexpr ll mod = 1e9+7;

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n,s,w,q;
    while(cin >> n >> s >> w >> q,n){
        ll g = s;
        vector<int> a(n);
        for(int i=0;i<n;i++){
            a[i] = (g/7) % 10;
            if(g&1) g = (g>>1)^w;
            else g = (g>>1);
        }
        // 場合分け
        if(q == 2 or q == 5){
            ll res = 0;
            ll pre = 0;
            for(int i=0;i<n;i++){
                if(a[i]) pre++;
                if(q == 2){
                    if(!(a[i]&1)) res += pre;
                }
                else{
                    if(a[i] == 0 or a[i] == 5) res += pre;
                }
            }
            cout << res << "\n";
        }
        else{
            vector<ll> sum(n+1);
            ll po = 1;
            for(int i=n-1;i>=0;i--){
                sum[i] = (sum[i+1] + a[i]*po) % q;
                po *= 10; if(po >= q) po %= q;
            }
            map<ll,ll> mp;
            ll res = 0;
            for(int i=0;i<n;i++){
                if(a[i]) mp[sum[i]]++;
                res += mp[sum[i+1]];
            }
            cout << res << "\n";
        }
    }
}
accuracy: 1
time_ms: 400
memory_kb: 10168
final_rank: 17

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

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  while (true) {
    int n, s, w, q;
    cin >> n >> s >> w >> q;
    if (n == 0) return 0;

    vector<int> a(n);
    int g = s;
    for (int i = 0; i < n; i++) {
      a.at(i) = (g / 7) % 10;
      if (g % 2 == 0) g = g / 2;
      else g = ((g / 2) ^ w);
    }

    if (q == 2 || q == 5) {
      int ans = 0, count = 0;
      for (int i = n - 1; i >= 0; i--) {
        if (a.at(i) % q == 0) count++;
        if (a.at(i) != 0) ans += count;
      }
      cout << ans << '\n';
      continue;
    }

    map<int, int> mp;
    mp[0]++;
    int now = 0, now10 = 1, ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      now += now10 * a.at(i);
      now %= q;
      now10 = (now10 * 10) % q;
      if (a.at(i) != 0) ans += mp[now];
      mp[now]++;
    }

    cout << ans << '\n';
  }
}
accuracy: 1
time_ms: 360
memory_kb: 7720
final_rank: 1

code_snippet: #line 1 "/Users/nok0/Documents/Programming/nok0/cftemp.hpp"
#include <bits/stdc++.h>
using namespace std;

#pragma region Macros
// rep macro
#define foa(v, a) for(auto &v : a)
#define REPname(a, b, c, d, e, ...) e
#define REP(...) REPname(__VA_ARGS__, REP3, REP2, REP1, REP0)(__VA_ARGS__)
#define REP0(x) for(int i = 0; i < (x); ++i)
#define REP1(i, x) for(int i = 0; i < (x); ++i)
#define REP2(i, l, r) for(int i = (l); i < (r); ++i)
#define REP3(i, l, r, c) for(int i = (l); i < (r); i += (c))
#define REPSname(a, b, c, ...) c
#define REPS(...) REPSname(__VA_ARGS__, REPS1, REPS0)(__VA_ARGS__)
#define REPS0(x) for(int i = 1; i <= (x); ++i)
#define REPS1(i, x) for(int i = 1; i <= (x); ++i)
#define RREPname(a, b, c, d, e, ...) e
#define RREP(...) RREPname(__VA_ARGS__, RREP3, RREP2, RREP1, RREP0)(__VA_ARGS__)
#define RREP0(x) for(int i = (x)-1; i >= 0; --i)
#define RREP1(i, x) for(int i = (x)-1; i >= 0; --i)
#define RREP2(i, r, l) for(int i = (r)-1; i >= (l); --i)
#define RREP3(i, r, l, c) for(int i = (r)-1; i >= (l); i -= (c))
#define RREPSname(a, b, c, ...) c
#define RREPS(...) RREPSname(__VA_ARGS__, RREPS1, RREPS0)(__VA_ARGS__)
#define RREPS0(x) for(int i = (x); i >= 1; --i)
#define RREPS1(i, x) for(int i = (x); i >= 1; --i)

// name macro
#define pb push_back
#define eb emplace_back
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define popcnt(x) __builtin_popcountll(x)
template <class T = int>
using V = std::vector<T>;
template <class T = int>
using VV = std::vector<std::vector<T>>;
template <class T>
using pqup = std::priority_queue<T, std::vector<T>, std::greater<T>>;
using ll = long long;
using ld = long double;
using int128 = __int128_t;
using pii = std::pair<int, int>;
using pll = std::pair<long long, long long>;

// input macro
template <class T, class U>
std::istream &operator>>(std::istream &is, std::pair<T, U> &p) {
	is >> p.first >> p.second;
	return is;
}
template <class T>
std::istream &operator>>(std::istream &is, std::vector<T> &v) {
	for(T &i : v) is >> i;
	return is;
}
std::istream &operator>>(std::istream &is, __int128_t &a) {
	std::string s;
	is >> s;
	__int128_t ret = 0;
	for(int i = 0; i < s.length(); i++)
		if('0' <= s[i] and s[i] <= '9')
			ret = 10 * ret + s[i] - '0';
	a = ret * (s[0] == '-' ? -1 : 1);
	return is;
}
namespace scanner {
void scan(int &a) { std::cin >> a; }
void scan(long long &a) { std::cin >> a; }
void scan(std::string &a) { std::cin >> a; }
void scan(char &a) { std::cin >> a; }
void scan(char a[]) { std::scanf("%s", a); }
void scan(double &a) { std::cin >> a; }
void scan(long double &a) { std::cin >> a; }
template <class T, class U>
void scan(std::pair<T, U> &p) { std::cin >> p; }
template <class T>
void scan(std::vector<T> &a) { std::cin >> a; }
void INPUT() {}
template <class Head, class... Tail>
void INPUT(Head &head, Tail &...tail) {
	scan(head);
	INPUT(tail...);
}
}  // namespace scanner
#define VEC(type, name, size)     \
	std::vector<type> name(size); \
	scanner::INPUT(name)
#define VVEC(type, name, h, w)                                    \
	std::vector<std::vector<type>> name(h, std::vector<type>(w)); \
	scanner::INPUT(name)
#define INT(...)     \
	int __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LL(...)            \
	long long __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define STR(...)             \
	std::string __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define CHAR(...)     \
	char __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define DOUBLE(...)     \
	double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LD(...)              \
	long double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)

// output-macro
template <class T, class U>
std::ostream &operator<<(std::ostream &os, const std::pair<T, U> &p) {
	os << p.first << " " << p.second;
	return os;
}
template <class T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &a) {
	for(int i = 0; i < int(a.size()); ++i) {
		if(i) os << " ";
		os << a[i];
	}
	return os;
}
std::ostream &operator<<(std::ostream &dest, __int128_t &value) {
	std::ostream::sentry s(dest);
	if(s) {
		__uint128_t tmp = value < 0 ? -value : value;
		char buffer[128];
		char *d = std::end(buffer);
		do {
			--d;
			*d = "0123456789"[tmp % 10];
			tmp /= 10;
		} while(tmp != 0);
		if(value < 0) {
			--d;
			*d = '-';
		}
		int len = std::end(buffer) - d;
		if(dest.rdbuf()->sputn(d, len) != len) {
			dest.setstate(std::ios_base::badbit);
		}
	}
	return dest;
}
template <class T>
void print(const T a) { std::cout << a << '\n'; }
template <class Head, class... Tail>
void print(Head H, Tail... T) {
	std::cout << H << ' ';
	print(T...);
}
template <class T>
void printel(const T a) { std::cout << a << '\n'; }
template <class T>
void printel(const std::vector<T> &a) {
	for(const auto &v : a)
		std::cout << v << '\n';
}
template <class Head, class... Tail>
void printel(Head H, Tail... T) {
	std::cout << H << '\n';
	printel(T...);
}
void Yes(const bool b = true) { std::cout << (b ? "Yes\n" : "No\n"); }
void No() { std::cout << "No\n"; }
void YES(const bool b = true) { std::cout << (b ? "YES\n" : "NO\n"); }
void NO() { std::cout << "NO\n"; }
void err(const bool b = true) {
	if(b) {
		std::cout << "-1\n", exit(0);
	}
}

//debug macro
namespace debugger {
template <class T>
void view(const std::vector<T> &a) {
	std::cerr << "{ ";
	for(const auto &v : a) {
		std::cerr << v << ", ";
	}
	std::cerr << "\b\b }";
}
template <class T>
void view(const std::vector<std::vector<T>> &a) {
	std::cerr << "{\n";
	for(const auto &v : a) {
		std::cerr << "\t";
		view(v);
		std::cerr << "\n";
	}
	std::cerr << "}";
}
template <class T, class U>
void view(const std::vector<std::pair<T, U>> &a) {
	std::cerr << "{\n";
	for(const auto &p : a) std::cerr << "\t(" << p.first << ", " << p.second << ")\n";
	std::cerr << "}";
}
template <class T, class U>
void view(const std::map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &p : m) std::cerr << "\t[" << p.first << "] : " << p.second << "\n";
	std::cerr << "}";
}
template <class T, class U>
void view(const std::pair<T, U> &p) { std::cerr << "(" << p.first << ", " << p.second << ")"; }
template <class T>
void view(const std::set<T> &s) {
	std::cerr << "{ ";
	for(auto &v : s) {
		view(v);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <class T>
void view(const T &e) { std::cerr << e; }
}  // namespace debugger
#ifdef LOCAL
void debug_out() {}
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
	debugger::view(H);
	std::cerr << ", ";
	debug_out(T...);
}
#define debug(...)                                                \
	do {                                                          \
		std::cerr << __LINE__ << " [" << #__VA_ARGS__ << "] : ["; \
		debug_out(__VA_ARGS__);                                   \
		std::cerr << "\b\b]\n";                                   \
	} while(false)
#else
#define debug(...) (void(0))
#endif

// vector macro
template <class T>
int lb(const std::vector<T> &a, const T x) { return std::distance((a).begin(), std::lower_bound((a).begin(), (a).end(), (x))); }
template <class T>
int ub(const std::vector<T> &a, const T x) { return std::distance((a).begin(), std::upper_bound((a).begin(), (a).end(), (x))); }
template <class T>
void UNIQUE(std::vector<T> &a) {
	std::sort(a.begin(), a.end());
	a.erase(std::unique(a.begin(), a.end()), a.end());
}
template <class T>
std::vector<T> press(std::vector<T> &a) {
	auto res = a;
	UNIQUE(res);
	for(auto &v : a)
		v = lb(res, v);
	return res;
}
#define SORTname(a, b, c, ...) c
#define SORT(...) SORTname(__VA_ARGS__, SORT1, SORT0, ...)(__VA_ARGS__)
#define SORT0(a) std::sort((a).begin(), (a).end())
#define SORT1(a, c) std::sort((a).begin(), (a).end(), [](const auto x, const auto y) { return x c y; })
template <class T>
void ADD(std::vector<T> &a, const T x = 1) {
	for(auto &v : a) v += x;
}
template <class T>
void SUB(std::vector<T> &a, const T x = 1) {
	for(auto &v : a) v -= x;
}
std::vector<std::pair<char, int>> rle(const string &s) {
	int n = s.size();
	std::vector<std::pair<char, int>> ret;
	for(int l = 0; l < n;) {
		int r = l + 1;
		for(; r < n and s[l] == s[r]; r++) {}
		ret.emplace_back(s[l], r - l);
		l = r;
	}
	return ret;
}
template <class T>
std::vector<std::pair<T, int>> rle(const std::vector<T> &v) {
	int n = v.size();
	std::vector<std::pair<T, int>> ret;
	for(int l = 0; l < n;) {
		int r = l + 1;
		for(; r < n and v[l] == v[r]; r++) {}
		ret.emplace_back(v[l], r - l);
		l = r;
	}
	return ret;
}
std::vector<int> iota(int n) {
	std::vector<int> p(n);
	std::iota(p.begin(), p.end(), 0);
	return p;
}
template <class T>
struct cum_vector {
public:
	cum_vector() = default;
	template <class U>
	cum_vector(const std::vector<U> &vec) : cum((int)vec.size() + 1) {
		for(int i = 0; i < (int)vec.size(); i++)
			cum[i + 1] = cum[i] + vec[i];
	}
	T prod(int l, int r) {
		return cum[r] - cum[l];
	}

private:
	std::vector<T> cum;
};

// math macro
template <class T, class U>
inline bool chmin(T &a, const U &b) { return a > b ? a = b, true : false; }
template <class T, class U>
inline bool chmax(T &a, const U &b) { return a < b ? a = b, true : false; }
template <class T>
T divup(T x, T y) { return (x + y - 1) / y; }
template <class T>
T POW(T a, long long n) {
	T ret = 1;
	while(n) {
		if(n & 1) ret *= a;
		a *= a;
		n >>= 1;
	}
	return ret;
}
// modpow
long long POW(long long a, long long n, const int mod) {
	long long ret = 1;
	a = (a % mod + mod) % mod;
	while(n) {
		if(n & 1) (ret *= a) %= mod;
		(a *= a) %= mod;
		n >>= 1;
	}
	return ret;
}
template <class T, class F>
T bin_search(T ok, T ng, const F &f) {
	while(abs(ok - ng) > 1) {
		T mid = (ok + ng) >> 1;
		(f(mid) ? ok : ng) = mid;
	}
	return ok;
}
template <class T, class F>
T bin_search(T ok, T ng, const F &f, int loop) {
	for(int i = 0; i < loop; i++) {
		T mid = (ok + ng) / 2;
		(f(mid) ? ok : ng) = mid;
	}
	return ok;
}

// others
struct fast_io {
	fast_io() {
		ios::sync_with_stdio(false);
		cin.tie(nullptr);
		cout << fixed << setprecision(15);
	}
} fast_io_;
const int inf = 1e9;
const ll INF = 1e18;
#pragma endregion

void main_();

int main() {
	main_();
	return 0;
}
#line 2 "a.cpp"

vector<int> gen(int n, int s, int w) {
	int g = s;
	vector<int> a(n);
	for(int i = 0; i < n; i++) {
		a[i] = (g / 7) % 10;
		if(g % 2 == 0)
			g /= 2;
		else
			g = (g / 2) ^ w;
	}
	return a;
}

void main_() {
	while(1) {
		INT(n, s, w, q);
		if(!n) break;
		auto a = gen(n, s, w);
		if(q == 2 or q == 5) {
			V<> valid(n);
			REP(i, n) { valid[i] = !!a[i]; }
			cum_vector<int> cum(valid);
			int res = 0;
			RREP(i, n) {
				if(a[i] % q) continue;
				res += cum.prod(0, i + 1);
			}
			print(res);
			continue;
		}
		map<int, int> memo;
		ll val = 0, base = 1, res = 0;
		memo[0] = 1;
		RREP(i, n) {
			val += (ll)a[i] * base;
			val %= q;
			base *= 10;
			base %= q;
			if(a[i]) res += memo[val];
			memo[val]++;
		}
		print(res);
	}
}
accuracy: 1
time_ms: 380
memory_kb: 7840
final_rank: 7

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

using ll = long long;
using PII = pair<ll, ll>;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
#define POPCOUNT(x) __builtin_popcount(x)
template <typename T> void chmin(T &a, const T &b) { a = min(a, b); }
template <typename T> void chmax(T &a, const T &b) { a = max(a, b); }

const ll INF = 1LL << 60;

struct FastIO {
    FastIO() {
        cin.tie(0);
        ios::sync_with_stdio(0);
    }
} fastiofastio;

const ll MOD = 1e9 + 7;

// BEGIN CUT
ll modpow(ll x, ll y, ll m) {
    ll a = 1, p = x;
    while (y > 0) {
        if (y % 2 == 0) {
            p = (p * p) % m;
            y /= 2;
        } else {
            a = (a * p) % m;
            y--;
        }
    }
    return a;
}
// END CUT

ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }

int A[100000];
ll B[100001];
ll mul[100000];

int main() {
    int N, S, W, Q;
    while (cin >> N >> S >> W >> Q, N) {
        int g = S;
        for (int i = 0; i < N; i++) {
            A[i] = (g / 7) % 10;
            if (g % 2 == 0) {
                g = (g / 2);
            } else {
                g = (g / 2) ^ W;
            }
        }
        if (Q == 2 || Q == 5) {
            int ans = 0;
            int k = 0;
            for (int i = 0; i < N; i++) {
                if (A[i] == 0) {
                    ans += k;
                } else {
                    if (A[i] % Q == 0)
                        ans += k + 1;
                    k++;
                }
            }
            cout << ans << '\n';
            continue;
        }
        mul[N - 1] = 1;
        for (int i = N - 2; i >= 0; i--) {
            mul[i] = (mul[i + 1] * 10) % Q;
        }
        memset(B, 0, sizeof(B));
        for (int i = 0; i < N; i++) {
            if (i > 0)
                B[i] = B[i - 1];
            (B[i] += A[i] * mul[i] % Q) %= Q;
        }
        map<int, int> cnt;
        int prev = 0;
        int ans = 0;
        for (int i = 0; i < N; i++) {
            ans += cnt[B[i]];
            if (A[i] != 0) {
                cnt[prev]++;
            }
            if (A[i] != 0 && A[i] % Q == 0)
                ans++;
            prev = B[i];
        }
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 440
memory_kb: 9388
final_rank: 19

code_snippet: #pragma GCC tag("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define DEBUG
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    int sz = a.size();
    for(auto itr = a.begin(); itr != a.end(); itr++){
		cout << *itr;
        sz--;
        if(sz) cout << " ";
	}
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){
	cout << a << " " << b << "\n";
}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
void mark() {cout << "#" << "\n";}
ll pcount(ll x) {return __builtin_popcountll(x);}
//#include <atcoder/maxflow>
//using namespace atcoder;
const int inf = (1<<30)-1;
const ll linf = 1LL<<61;
const int MAX = 5050000;
int dy[8] = {0,1,0,-1,1,-1,-1,1};
int dx[8] = {-1,0,1,0,1,-1,1,-1};
const double pi = acos(-1);
const double eps = 1e-9;
const int mod = 1e9 + 7;
//const int mod = 998244353;

ll modpow(ll x, ll n, ll mod){
    ll res = 1;
    while(n > 0){
        if(n & 1) res = res * x % mod;
        x = x * x % mod;
        n >>= 1;
    }
    return res;
}

int main(){
    while(1){
        ll n,s,w,p; cin >> n >> s >> w >> p;
        if(!n) break;
        vl a(n);
        ll g = s;
        rep(i,n){
            a[i] = (g/7) % 10;
            if(g % 2 == 0) g = g/2;
            else g = (g/2) ^ w;
        }
        ll inv10 = modpow(10,p-2,p);
        ll ans = 0;
        if(p == 2 || p == 5){
            ll cnt = 0;
            rep(i,n){
                if(a[i] == 0) ans += cnt;
                else{
                    cnt++;
                    if(a[i] % p == 0) ans += cnt;
                }
            }
        }else{
            map<ll,ll> mp;
            ll now = 0;
            ll mul = 1;
            mp[0]++;
            rep(i,n){
                if(a[i] == 0) ans--;
                now = (now * 10 + a[i]) % p;
                ll tmp = now * mul % p;
                if(mp.count(tmp)) ans += mp[tmp];
                if(a[i] != 0) mp[tmp]++;
                mul = mul * inv10 % p;
            }
        }
        cout << ans << "\n";
    }
}
accuracy: 1
time_ms: 430
memory_kb: 9288
final_rank: 18

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

int main() {
    int N, S, W, Q;
    while (cin >> N >> S >> W >> Q, N) {
        vector<int> a(N);
        int g = S;
        for (int i = 0; i < N; i++) {
            a[i] = (g / 7) % 10;
            if (g % 2 == 0) {
                g = (g / 2);
            } else {
                g = (g / 2) ^ W;
            }
        }
        int ans = 0;
        if (10 % Q == 0) {
            int maine = 0;
            for (int i = N - 1; i >= 0; i--) {
                maine += (a[i] % Q == 0);
                if (a[i])
                    ans += maine;
            }
        } else {
            map<int, int> maine;
            maine[0]++;
            int book = 0, tens = 1;
            for (int i = N - 1; i >= 0; i--) {
                (tens *= 10) %= Q;
                (book += tens * a[i]) %= Q;
                if (a[i] != 0)
                    ans += maine[book];
                maine[book]++;
            }
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 380
memory_kb: 7668
final_rank: 6

code_snippet: #include <iostream>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;

bool solve() {
    int n;
    cin >> n;
    if (n == 0) return false;

    vector<int> ds(n);
    {
        int s, w;
        cin >> s >> w;

        for (auto& d : ds) {
            d = (s / 7) % 10;

            if (s % 2 == 0) {
                s = s / 2;
            } else {
                s = (s / 2) ^ w;
            }
        }
    }

    int p;
    cin >> p;

    int ans = 0;
    if (p == 2 || p == 5) {
        int acc = 0;
        for (auto d : ds) {
            if (d != 0) ++acc;
            if (d % p == 0) ans += acc;
        }
    } else {
        reverse(ds.begin(), ds.end());
        map<int, int> cnt;

        int sum = 0, deg = 1;
        for (auto d : ds) {
            ++cnt[sum];
            (sum += d * deg) %= p;
            (deg *= 10) %= p;

            if (d != 0 && cnt.count(sum)) ans += cnt[sum];
        }
    }

    cout << ans << "\n";
    return true;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    while (solve()) {}

    return 0;
}
accuracy: 1
time_ms: 370
memory_kb: 7692
final_rank: 5

code_snippet: #include<iostream>
#include<map>
using namespace std;
long modpow(long a,long b,long mod){return b?modpow(a*a%mod,b/2,mod)*(b%2?a:1)%mod:1%mod;}
int N,S,W,Q;
main()
{
	while(cin>>N>>S>>W>>Q,N)
	{
		long inv=modpow(10,Q-2,Q),pinv=1;
		long ans=0,now=0,cnt=0;
		map<int,int>mp;
		for(int i=0;i<N;i++)
		{
			int a=S/7%10;
			if(a!=0)
			{
				mp[now]++;
				cnt++;
			}
			now=(now+pinv*a)%Q;
			pinv=pinv*inv%Q;
			if(Q==2||Q==5)
			{
				if(a%Q==0)ans+=cnt;
			}
			else ans+=mp[now];
			if(S%2==0)S/=2;
			else S=S/2^W;
		}
		cout<<ans<<endl;
	}
}
accuracy: 1
time_ms: 410
memory_kb: 7304
final_rank: 10

code_snippet: #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
#include "numeric"
#include "cassert"
#include "ctime"

using namespace std;

//constexpr long long int MOD = 1000000007;
//constexpr int MOD = 1000000007;
//constexpr int MOD = 998244353;
constexpr long long int MOD = 998244353;
constexpr double EPS = 1e-12;

//int N, M, K, T, H, W, L, R;
long long int N, M, K, T, H, W, L, R;


int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);

	while (cin >> N >> L >> M >> K, N) {
		vector<int>v(N + 1);
		for (int i = 1; i <= N; i++) {
			v[i] = (L / 7) % 10;
			if (L & 1)L = (L / 2) ^ M;
			else L >>= 1;
		}
		if (K == 2 || K == 5) {
			long long int ans = 0;
			int num = 0;
			for (int i = 1; i <= N; i++) {
			//	cout << v[i];
				if (v[i]) {
					num++;
					if (v[i] % K == 0) {
						ans += num;
					}
				}
				else {
					ans += num;
				}
			}
			cout << ans << endl;
			continue;
		}
		map<int, int>mp;
		long long int ans = 0;
		mp[0]++;
		long long int num = 0;
		long long int by = 1;
		for (int i = N; i > 0; i--) {
			num += by * v[i];
			num %= K;
			if (v[i]) {
				ans += mp[num];
			}
			mp[num]++;
			by *= 10;
			by %= K;
		}
		cout << ans << endl;
	}
}
accuracy: 1
time_ms: 410
memory_kb: 7264
final_rank: 9