#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>

using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);

#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, n) for (int i = (s); i < (int)(n); i++)
#define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++)
#define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++)
#define MEMSET(v, h) memset((v), h, sizeof(v))

ll n, m, M;
ll u, v;

ll calc(ll first, ll left, ll right) {
  //cout << first << " " << left << " " << right << endl;
  assert(left <= right);
  if (u == v && u % 2 != first % 2) { return 0; }
  if (first + right * 2 < u || v < first + left * 2) { return 0; }
  ll S = max(u + ((u % 2 == first % 2) ? 0 : 1), first + left * 2);
  ll E = min(v - ((v % 2 == first % 2) ? 0 : 1), first + right * 2);
  if (S > E) { return 0; }
  ll N = (E - S) / 2 + 1;
  return (N % M) * ((S % M + N % M + M - 1) % M) % M;
}

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  while (cin >> n >> m >> M) {
    REP(i, m) {
      ll l, r;
      cin >> l >> r >> u >> v;
      l--; r--;
      ll ans = 0;
      ll center = (n + 1) / 2;
      if (l < center) {
        ans += calc(1, l, min(r, center - 1));
      }
      if (r >= center) {
        ans += calc(2, max(l - center, 0LL), r - center);
      }
      ans %= M;
      printf("%d\n", (int)ans);
    }
  }
}


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>

using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);

#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, n) for (int i = (s); i < (int)(n); i++)
#define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++)
#define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++)
#define MEMSET(v, h) memset((v), h, sizeof(v))

ll n, m, M;
ll u, v;

ll Arith(ll first, ll diff, ll left, ll right) {
  //cout << first << " " << left << " " << right << endl;
  assert(left <= right);
  //if (u == v && u % 2 != first % 2) { return 0; }
  if (first + right * diff < u || v < first + left * diff) { return 0; }
  ll S = max(u, first + left * diff);
  ll E = min(v, first + right * diff);
  {
    ll plus = first % diff - S % diff;
    if (plus < 0) { plus += diff; }
    S += plus;
    plus = E % diff - first % diff;
    if (plus < 0) { plus += diff; }
    E -= plus;
  }
  //cout << S << " "<< E << endl;
  if (S > E) { return 0; }
  ll N = (E - S) / diff + 1;
  if (N % 2 == 0) {
    return (S % M * (N % M) % M + N / 2 % M * ((N - 1) % M) % M * (diff % M)) % M;
  } else {
    return (S % M * (N % M) % M + N % M * ((N - 1) / 2 % M) % M * (diff % M)) % M;
  }
}

ll calc(ll first, ll diff, ll l, ll r, ll w) {
  if (l == 0 && r == w - 1) {
    return Arith(first, diff, l, r);
  }
  ll ret = 0;
  ll center = (w + 1) / 2;
  if (l < center) {
    ret += calc(first, diff * 2, l, min(r, center  - 1), center);
  }
  if (r >= center) {
    ret += calc(first + diff, diff * 2, max(l - center, 0LL), r - center, w - center);
  }
  ret %= M;
  return ret;
}

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  while (cin >> n >> m >> M) {
    REP(i, m) {
      ll l, r;
      cin >> l >> r >> u >> v;
      l--; r--;
      ll ans = calc(1, 1, l, r, n);
      printf("%d\n", (int)ans);
    }
  }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))% (2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    while(m--){
        if(m%10000==0&&m>0) {  mp.clear(); cnt++; printf("%d\n",cnt);}
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))% (2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        if(i&&(i%10000==0)) {  return 0;}
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (mod<<1) * ((v-u+1) % (mod<<1))) % (mod<<1) >>1 ,v-u+1);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)>>1;
    LL x=(u>>1)+1 , y=(v+1)>>1;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+((LL)res.ans<<1)-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)>>1 , y=v>>1;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+((LL)res.ans<<1))%mod;
            ans.cnt+=res.cnt;
        }
    }
    if(n<100000000000000000LL) mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        if(i&&i%50000==0)   mp.clear();
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    LL ans,cnt;
    tt() {}
    tt(LL ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        res=dfs(x,y,f,L,R);
        ans.ans=(ans.ans+2*res.ans-res.cnt)%mod;
        ans.cnt+=res.cnt;
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    while(m--){
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
int mod;
struct node
{
    int u,v,l,r;
    node () {}
    node (int u,int v,int l,int r) : u(u) ,v(v) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(l!=s.l) return l<s.l;
        return r<s.r;
    }
};
map<node ,int > mp;
int dfs(int u,int v,int l,int r)
{
    node cur=node(u,v,l,r);
    //printf("%d %d %d %d\n",u,v,l,r);
    if(v==1) return 1;
    if(mp.find(cur)!=mp.end()) return mp[cur];
    int f=(v+1)/2;
    int x=u/2+1 , y=(v+1)/2;
    int ans=0;
    int L=l,R=r;
    if(x<=y) {
        int res;
        R=min(r,y);
        if(L<=R) {
            res=dfs(x,y,L,R);
            ans=(ans+2*res-1)%mod;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        int res;
        l-=f;
        r-=f;
        l=max(l,1);
        if(l<=r) {
            res=dfs(x,y,l,r);
            ans=(ans+2*res)%mod;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    LL n;
    int m;
    scanf("%I64d%d%d",&n,&m,&mod);
    while(m--){
        int u,v,l,r;
        scanf("%d%d%d%d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v) printf("%d\n",(dfs(u,v,l,r)+mod)%mod);
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
int mod;
struct node
{
    LL u,v,l,r;
    node () {}
    node (LL u,LL v,LL l,LL r) : u(u) ,v(v) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(l!=s.l) return l<s.l;
        return r<s.r;
    }
};
struct tt
{
    LL ans;
    LL cnt;
    tt() {}
    tt(LL ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL l,LL r)
{
    node cur=node(u,v,l,r);
   // printf("%d %d %d %d\n",u,v,l,r);
    if(v==1) return tt(1,1);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(v+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,y);
        if(L<=R) {
            res=dfs(x,y,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        if(l<=r) {
            res=dfs(x,y,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    LL n;
    int m;
    scanf("%I64d%d%d",&n,&m,&mod);
    while(m--){
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v) {
            int ans=dfs(u,v,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))% (2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        if(i==50000) {  return 0;}
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))%(2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    while(m--){
        if(m%1000==0) mp.clear();
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))%(2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    while(m--){
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (mod<<1) * ((v-u+1) % (mod<<1))) % (mod<<1) >>1 ,v-u+1);
    LL f=(n+1)>>1;
    LL x=(u>>1)+1 , y=(v+1)>>1;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+((LL)res.ans<<1)-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)>>1 , y=v>>1;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+((LL)res.ans<<1))%mod;
            ans.cnt+=res.cnt;
        }
    }
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))% (2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        if(i&&i%30000==0)   mp.clear();
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (2*mod) * ((v-u+1) % (2*mod)))% (2*mod) / 2 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+2LL*res.ans-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2LL*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        if(i&&i%25000==0)   mp.clear();
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
           printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    LL ans,cnt;
    tt() {}
    tt(LL ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)/2;
    LL x=u/2+1 , y=(v+1)/2;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        res=dfs(x,y,f,L,R);
        ans.ans=(ans.ans+2*res.ans-res.cnt)%mod;
        ans.cnt+=res.cnt;
    }
    x=(u+1)/2 , y=v/2;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+2*res.ans)%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    while(m--){
        mp.clear();
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
LL mod;
struct node
{
    LL u,v,l,r,n;
    node () {}
    node (LL u,LL v,LL n,LL l,LL r) : u(u) ,v(v) ,n(n) ,l(l) ,r(r) {}
    bool operator < (const node & s) const
    {
        if(u!=s.u) return u<s.u;
        if(v!=s.v) return v<s.v;
        if(n!=s.n) return n<s.n;
        if(l!=s.l) return l<s.l;
        return r<s.r;

    }
};
struct tt
{
    int ans;
    LL cnt;
    tt() {}
    tt(int ans,LL cnt) : ans(ans) , cnt(cnt) {}
};
map<node ,tt > mp;
tt dfs(LL u,LL v,LL n,LL l,LL r)
{
    node cur=node(u,v,n,l,r);

    //printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(v==1) {
        if(l==1) return tt(1,1);
        return tt(0,0);
    }
    if(l==1&&r==n) return tt( ((u+v) % (mod<<1) * ((v-u+1) % (mod<<1)))% (mod<<1) >>1 ,v-u+1);
   // printf("%I64d %I64d %I64d %I64d %I64d\n",u,v,n,l,r);
    if(mp.find(cur)!=mp.end()) return mp[cur];
    LL f=(n+1)>>1;
    LL x=(u>>1)+1 , y=(v+1)>>1;
    tt ans=tt(0,0);
    LL L=l,R=r;
    if(x<=y) {
        tt res;
        R=min(r,f);
        if(L<=R){
            res=dfs(x,y,f,L,R);
            ans.ans=(ans.ans+((LL)res.ans<<1)-res.cnt)%mod;
            ans.cnt+=res.cnt;
        }
    }
    x=(u+1)>>1 , y=v>>1;
    if(x<=y) {
        tt res;
        l-=f;
        r-=f;
        l=max(l,1LL);
        r=min(n-f,r);
        if(l<=r) {
            res=dfs(x,y,n-f,l,r);
            ans.ans=(ans.ans+((LL)res.ans<<1))%mod;
            ans.cnt+=res.cnt;
        }
    }
    mp[cur]=ans;
    return ans;
}
int main()
{
    //freopen("1.in","r",stdin);
    LL n;
    int m;
    scanf("%I64d%d%I64d",&n,&m,&mod);
    int cnt=0;
    for(int i=0;i<m;i++){
        if(i&&i%35000==0)   mp.clear();
        LL u,v,l,r;
        scanf("%I64d%I64d%I64d%I64d",&l,&r,&u,&v);
        if(v>n) v=n;
        if(u<=v&&l<=r) {
            LL ans=dfs(u,v,n,l,r).ans;
            printf("%I64d\n",(ans+mod)%mod);
        }
        else puts("0");
    }
}


//In the name of God
#include <iostream>
using namespace std;

typedef long long ll;

ll mod, n, cnt;
int m;

ll func(ll b, ll e, ll l, ll r, ll u, ll v) {
	v = min(v, e - b);
//	cerr << b << ' ' << e << ' ' << l << ' ' << r << ' ' << u << ' ' << v << '\n';
	if (v < u) {
//		cerr << "NO\n";
		throw ~0;
	}
	ll m = b + e >> 1;
	if (e < l || r < b || e < u) {
//		cerr << "NO!\n";
		throw ~0;
	}
	ll x, y;
	if (l <= b && e <= r) {
		cnt += v - u + 1;
//		cerr << "YES: " << v - u + 1 << ' ' << (v * (v + 1) - u * (u - 1)) / 2 << '\n';
//		return (v * (v + 1) - u * (u - 1)) / 2;
		if (v & 1)
			x = (v + 1) / 2 % mod * v % mod;
		else
			x = v / 2 % mod * (v + 1) % mod;
		if (u & 1)
			y = (u - 1) / 2 % mod * u % mod;
		else
			y = u / 2 % mod * (u - 1) % mod;
		return (x - y + mod) % mod;
	}
	try {
		x = (func(b, m, l, r, u + (u & 1) >> 1, v >> 1) << 1) % mod;
	}
	catch (int exp) {
		x = exp;
	}
	try {
		y = (func(m + 1, e, l, r, u >> 1, v - (v & 1 ^ 1) >> 1) << 1 | 1) % mod;
	}
	catch (int exp){
		y = exp;
	}
	if (y == ~0 && x == ~0)
		throw ~0;
	return (max(x, 0ll) + max(y, 0ll)) % mod;
}
	//FIXME: mod!
int main() {
	ios_base::sync_with_stdio(false);
	cin >> n >> m >> mod;
	for (int i = 0; i < m; i++) {
		ll l, r, u, v;
		cnt = 0;
		cin >> l >> r >> u >> v;
		l--, r--, u--, v--;
		ll res;
		try {
			res = (func(0, n - 1, l, r, u, v) + cnt) % mod;
		}
		catch (int exp){
			res = 0;
		}
		cout << res << '\n';
	}
	return 0;
}


//In the name of God
#include <iostream>
using namespace std;

typedef long long ll;
typedef pair<ll, ll> pll;

ll mod, n;
int m;

pll func(ll b, ll e, ll l, ll r, ll u, ll v) {
	v = min(v, e - b);
	u = max(u, 0ll);
	if (v < u || e < l || r < b)
		return pll(0, 0);
	if (l <= b && e <= r) {
		ll x, y;
		if (v & 1)
			x = ((v + 1) / 2 % mod) * (v % mod) % mod;
		else
			x = (v / 2 % mod) * ((v + 1) % mod) % mod;
		if (u & 1)
			y = ((u - 1) / 2 % mod) * (u % mod) % mod;
		else
			y = (u / 2 % mod) * ((u - 1) % mod) % mod;
		return pll((x - y + mod) % mod, (v - u + 1) % mod);
	}
	ll m = b + e >> 1;
	pll x = func(b, m, l, r, u + (u & 1) >> 1, v >> 1);
	x.first *= 2;
	pll y = func(m + 1, e, l, r, u >> 1, v - (v & 1 ^ 1) >> 1);
	y.first = y.first * 2 + y.second;
	return pll((x.first + y.first) % mod, (x.second + y.second) % mod);
}
int main() {
	ios_base::sync_with_stdio(false);
	cin >> n >> m >> mod;
	while (m--) {
		ll l, r, u, v;
		cin >> l >> r >> u >> v;
		l--, r--, u--, v--;
		pll res = func(0, n - 1, l, r, u, v);
		cout << (res.first + res.second) % mod << '\n';
	}
	return 0;
}


//In the name of God
#include <iostream>
using namespace std;

typedef long long ll;
typedef pair<ll, ll> pll;

ll mod, n;
int m;

pll func(ll b, ll e, ll l, ll r, ll u, ll v) {
	v = min(v, e - b);
	u = max(u, 0ll);
	if (v < u ||e < l || r < b)
		return pll(0, 0);
	if (l <= b && e <= r) {
		ll x, y;
		if (v & 1)
			x = (v + 1) / 2 % mod * v % mod;
		else
			x = v / 2 % mod * (v + 1) % mod;
		if (u & 1)
			y = (u - 1) / 2 % mod * u % mod;
		else
			y = u / 2 % mod * (u - 1) % mod;
		return pll((x - y + mod) % mod, (v - u + 1) % mod);
	}
	ll m = b + e >> 1;
	pll x = func(b, m, l, r, u + (u & 1) >> 1, v >> 1);
	x.first *= 2;
	pll y = func(m + 1, e, l, r, u >> 1, v - (v & 1 ^ 1) >> 1);
	y.first = y.first * 2 + y.second;
	return pll((x.first + y.first) % mod, (x.second + y.second) % mod);
}
int main() {
	ios_base::sync_with_stdio(false);
	cin >> n >> m >> mod;
	for (int i = 0; i < m; i++) {
		ll l, r, u, v;
		cin >> l >> r >> u >> v;
		l--, r--, u--, v--;
		pll res = func(0, n - 1, l, r, u, v);
		cout << (res.first + res.second) % mod << '\n';
	}
	return 0;
}


//In the name of God
#include <iostream>
using namespace std;

typedef long long ll;

ll mod, n, cnt;
int m;

ll func(ll b, ll e, ll l, ll r, ll u, ll v) {
//	cerr << b << ' ' << e << ' ' << l << ' ' << r << ' ' << u << ' ' << v << '\n';
	if (v < u) {
//		cerr << "NO\n";
		throw ~0;
	}
	ll m = b + e >> 1;
	if (e < l || r < b || e < u) {
//		cerr << "NO!\n";
		throw ~0;
	}
	ll x, y;
	if (l <= b && e <= r) {
		v = min(v, e - b);
		cnt += v - u + 1;
//		cerr << "YES: " << v - u + 1 << ' ' << (v * (v + 1) - u * (u - 1)) / 2 << '\n';
//		return (v * (v + 1) - u * (u - 1)) / 2;
		if (v & 1)
			x = (v + 1) / 2 % mod * v % mod;
		else
			x = v / 2 % mod * (v + 1) % mod;
		if (u & 1)
			y = (u - 1) / 2 % mod * u % mod;
		else
			y = u / 2 % mod * (u - 1) % mod;
		return (x - y + mod) % mod;
	}
	try {
		x = (func(b, m, l, r, u + (u & 1) >> 1, v >> 1) << 1) % mod;
	}
	catch (int exp) {
		x = exp;
	}
	try {
		y = (func(m + 1, e, l, r, u >> 1, v - (v & 1 ^ 1) >> 1) << 1 | 1) % mod;
	}
	catch (int exp){
		y = exp;
	}
	if (y == ~0 && x == ~0)
		throw ~0;
	return (max(x, 0ll) + max(y, 0ll)) % mod;
}
	//FIXME: mod!
int main() {
	ios_base::sync_with_stdio(false);
	cin >> n >> m >> mod;
	for (int i = 0; i < m; i++) {
		ll l, r, u, v;
		cnt = 0;
		cin >> l >> r >> u >> v;
		l--, r--, u--, v--;
		ll res;
		try {
			res = (func(0, n - 1, l, r, u, v) + cnt) % mod;
		}
		catch (int exp){
			res = 0;
		}
		cout << res << '\n';
	}
	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
ll n,m,mod;
ll gp(ll lo,ll hi,ll br){
  if(lo>hi)return 0;
  return ((((lo+hi)/2)%mod ) * (br%mod))%mod;
}
ll sum(ll beg,ll d,ll br,ll lo,ll hi){
  ll end=beg+(br-1)*d;
  if(end>hi){end-=((end-hi)/d)*d; if(end>hi)end-=d;}
  if(beg<lo){beg+=((lo-beg)/d)*d; if(beg<lo)beg+=d;}
  return gp(beg,end,(end-beg)/d+1);
}
ll f(ll beg,ll d,ll br,ll l,ll r,ll lo,ll hi){
  if(br<=0 || l>r || br<l)return 0;
  if(l==1 && br<=r)return sum(beg,d,br,lo,hi);
  ll brc=br/2,brn=br-brc;
  return ( f(beg,2*d,brn,l,min(r,brn),lo,hi)+f(beg+d,2*d,brc,max(l,brn+1)-brn,r-brn,lo,hi) )%mod;
}
int main(){
  scanf("%I64d %I64d %I64d",&n,&m,&mod);
  while(m--){
   ll a,b,c,d; scanf("%I64d %I64d %I64d %I64d",&a,&b,&c,&d);
   printf("%I64d\n",f(1,1,n,a,b,c,d));
            }
  return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll n,m,mod ,brc,brn;
ll sum(ll f, ll t){
  ll s1f=0,s1t;
  if(f){
   --f;
   if(f%2)s1f=(f%mod)*(((f+1)/2)%mod) %mod;
   else s1f=((f/2)%mod)*((f+1)%mod) %mod;
       }
  if(t%2)s1t=(t%mod)*(((t+1)/2)%mod) %mod;
  else s1t=((t/2)%mod)*((t+1)%mod) %mod;
  return (s1t-s1f)%mod;
}
ll sc(ll f,ll t){
  if(f&1)++f; if(t&1)--t;
  if(f>t)return 0;
  return (2*sum(f/2,t/2))%mod;
}
ll sn(ll f,ll t){
  if(!(f&1))++f; if(!(t&1))--t;
  if(f>t)return 0;
  return (sum(f,t)-sc(f+1,t-1))%mod;
}
ll interval(ll f,ll t, ll u,ll v){
  if(f>brn){
   f-=brn; t-=brn;
   return sc(max(2*f,u),min(2*t,v));
           }
  if(t<=brn)return sn(max(2*f-1,u),min(2*t-1,v));
  return (sn(max(2*f-1,u),min(2*brn-1,v))+interval(brn+1,t,u,v))%mod;
}
int main(){
  cin>>n>>m>>mod;
  brc=n/2; brn=n-brc;
  while(m--){
   ll a,b,c,d; cin>>a>>b>>c>>d;
   cout<<(mod+interval(a,b,c,d))%mod<<'\n';
            }
  //system("pause");
  return 0;
}


def binarySearch(val, x, y):
    if val < listPrice[x]:
        return x - 1
    if x == y:
        return x if val >= listPrice[x] else x - 1
    m = x + (y - x) // 2
    if val > listPrice[m]:
        return binarySearch(val, m + 1, y)
    elif val < listPrice[m]:
        return binarySearch(val, x, m - 1)
    else:
        return m

input()
listPrice = list(map(int, input().split()))
listPrice.sort()
n = int(input())
for _ in range(n):
    m = int(input())
    result=binarySearch(m, 0, len(listPrice) - 1)
    while result<len(listPrice)  and m>=listPrice[result]:
        result+=1
    print(result)


def binarySearch(val, x, y):
    if val < listPrice[x]:
        return x - 1
    if x == y:
        return x if val >= listPrice[x] else x - 1
    m = x + (y - x) // 2
    if val >= listPrice[m]:
        return binarySearch(val, m + 1, y)
    else:
        return binarySearch(val, x, m - 1)

input()
listPrice = list(map(int, input().split()))
listPrice.sort()
n = int(input())
for _ in range(n):
    m = int(input())
    result=binarySearch(m, 0, len(listPrice) - 1)
    while result<len(listPrice)  and m>=listPrice[result]:
        result+=1
    print(result if result>0 else 0)


def binarySearch(val, x, y):
    if val < listPrice[x]:
        return x - 1
    if x == y:
        return x if val >= listPrice[x] else x - 1
    m = x + (y - x) // 2
    if val >= listPrice[m]:
        return binarySearch(val, m + 1, y)
    else:
        return binarySearch(val, x, m - 1)

input()
listPrice = list(map(int, input().split()))
listPrice.sort()
n = int(input())
for _ in range(n):
    m = int(input())
    if m > listPrice[-1]:
        result = len(listPrice)
    elif m < listPrice[0]:
        result = 0
    else:
        result = binarySearch(m, 0, len(listPrice) - 1)
        while result < len(listPrice) and m >= listPrice[result]:
            result += 1
    print(result)


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))

    t=t+1


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
shop=[0]*q
t=0
while t<q:
    m=int(input())
    shop[t]=sum(list(map(lambda x:x<=m,price)))
    t=t+1

print('\n'.join(shop))


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
shop=[]
t=0
while t<q:
    shop.append(int(input()))
    t=t+1

for i in shop:
    print(sum(list(map(lambda x:x<=i,price))))


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

MAX=max(price)+1
shop=[0]*(MAX)
for i in price:
    shop[i]+=1
for i in range(1,MAX):
    shop[i]+=shop[i-1]
q=int(input())

while q>0:
    m=int(input())
    if m>max(price):
        m=max(price)
    print(shop[m])
    q=q-1


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
shop=[0]*q
t=0
while t<q:
    m=int(input())
    shop[t]=str(sum(list(map(lambda x:x<=m,price))))
    t=t+1

print('\n'.join(shop))


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

shop=[0]*(max(price)+1)
for i in price:
    shop[i]=shop[i]+1
for i in range(1,max(price)+1):
    shop[i]=shop[i]+shop[i-1]
q=int(input())
t=0
while t<q:
    m=int(input())
    if m>max(price):
        m=max(price)
    print(shop[m])
    t=t+1


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

shop=[0]*(max(price)+1)
for i in price:
    shop[i]+=1
for i in range(1,max(price)+1):
    shop[i]+=shop[i-1]
q=int(input())
t=0
while t<q:
    m=int(input())
    if m>max(price):
        m=max(price)
    print(shop[m])
    t=t+1


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

shop=[0]*(max(price)+1)
for i in price:
    shop[i]=1
for i in range(1,max(price)+1):
    shop[i]=shop[i]+shop[i-1]
q=int(input())
t=0
while t<q:
    m=int(input())
    print(shop[m])
    t=t+1


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

q=int(input())
shop=[0]*q
t=0
while t<q:
    m=int(input())
    shop[t]=str(sum(list(map(lambda x:x<=m,price))))
    t=t+1

print('\n'.join(shop))


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

MAX=max(price)+1
shop=[0]*(MAX)
for i in price:
    shop[i]+=1
for i in range(1,MAX):
    shop[i]+=shop[i-1]
q=int(input())

while q>0:
    m=int(input())
    if m>MAX-1:
        m=MAX-1
    print(shop[m])
    q=q-1


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 22:42:48 2018

@author: Quaint Sun
"""

'''
n=int(input())
price=[int(i) for i in input().split()]

q=int(input())
t=0
while t<q:
    m=int(input())
    print(sum(list(map(lambda x:x<=m,price))))
    t=t+1
    '''

n=int(input())
price=list(map(int,input().split()))

shop=[0]*(max(price)+1)
for i in price:
    shop[i]=1
for i in range(1,max(price)+1):
    shop[i]=shop[i]+shop[i-1]
q=int(input())
t=0
while t<q:
    m=int(input())
    if m>max(price):
        m=max(price)
    print(shop[m])
    t=t+1


n=int(input())
L=[0]*(10**5+1)

for k in map(int,input().split()):
    L[k]=1
q=int(input())
for j in range(q):
    a=int(input())
    print(sum(L[0:a+1]))


n=int(input())
L=[0]*(10**5+1)
for k in map(int,input().split()):
    L[k-1]+=1
q=int(input())
for j in range(q):
    a=int(input())
    if(a>=(10**5)):
        print(10**5)
    else:
        print(sum(L[0:a]))


n=int(input())
L=sorted(map(int,input().split()))
L1=[0]*(10**5+1)
c=1
for k in range(0,n-1):
    for j in range(L[k],L[k+1]+1):
        L1[j]=c
    c+=1
for i in range(L[n-1],10**5+1):
    L1[i]=c
q=int(input())

for h in range(q):
    a=int(input())
    if(a>=10**5):
        print(n)
    else:
        print(L1[a])


n=int(input())
L=sorted(map(int,input().split()))
L1=[0]*(10**5+1)
c=1
for k in range(0,n-1):
    for j in range(L[k],L[k+1]+1):
        L1[j]=c
    c+=1
for i in range(L[n-1],10**5+1):
    L1[i]=c
q=int(input())

for h in range(q):
    a=int(input())
    if(a>=10**5):
        print(10**5)
    else:
        print(L1[a])


n=int(input())
L=list(map(int,input().split()))
q=int(input())
for k in range(q):
    a=int(input())
    c=0
    for j in L:
        if(j<=a):
            c+=1
    print(c)


n=int(input())
L=[0]*(10**5+1)
for k in map(int,input().split()):
    L[k-1]+=1
q=int(input())
for j in range(q):
    a=int(input())
    print(L[0:a])
    print(sum(L[0:a]))


n=int(input())
L=[0]*(10**5+1)
for k in map(int,input().split()):
    L[k-1]+=1
q=int(input())
for j in range(q):
    a=int(input())
    print(sum(L[0:a]))


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
mi = x.count(minn)
ans = []
liste = []
for i in range(d):
    m = int(input())
    if m in liste:
        ans.append(ans[liste.index(m)])
    else:
        liste.append(m)
        if m >= maxx:
            ans.append(n)
        elif m < minn:
            ans.append(0)
        elif m == minn:
            ans.append(mi)
        else:
            ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
mi = x.count(minn)
ans = []
for i in range(d):
    m = int(input())
    if m >= maxx:
        ans.append(n)
    elif m < minn:
        ans.append(0)
    elif m == minn:
        ans.append(mi)
    else:
        ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
mi = x.count(minn)
ans = []
l = []
for i in range(d):
    m = int(input())
    if m in l:
        ans.append(ans[l.index(m)])
    else:
        l.append(m)
        if m >= maxx:
            ans.append(n)
        elif m < minn:
            ans.append(0)
        elif m == minn:
            ans.append(mi)
        else:
            ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
ans = []
for i in range(d):
    m = int(input())
    if m >= maxx:
        ans.append(n)
    elif m < minn:
        ans.append(0)
    elif m == minn:
        ans.append(x.count(minn))
    else:
        ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
ans = []
for i in range(d):
    m = int(input())
    if m > maxx:
        ans.append(n)
    elif m < minn:
        ans.append(0)
    else:
        ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


import bisect
n = int(input())
x = [int(elt) for elt in input().split(" ")]
x.sort()
d = int(input())
maxx = max(x)
minn = min(x)
mi = x.count(minn)
ans = []
liste = {}
for i in range(d):
    m = int(input())
    ans.append(bisect.bisect_right(x,m,hi=n))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
mi = x.count(minn)
ans = []
liste = {}
for i in range(d):
    m = int(input())
    if m in liste.items():
        ans.append(liste[m])
    else:
        if m >= maxx:
            ans.append(n)
        elif m < minn:
            ans.append(0)
        elif m == minn:
            ans.append(mi)
        else:
            ans.append(sum(m >= y for y in x))
            liste[m] = ans[-1]
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
ans = []
l = []
for i in range(d):
    m = int(input())
    if m in l:
        ans.append(ans[l.index(m)])
    else:
        l.append(m)
        if m >= maxx:
            ans.append(n)
        elif m < minn:
            ans.append(0)
        elif m == minn:
            ans.append(x.count(minn))
        else:
            ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
maxx = max(x)
minn = min(x)
mi = x.count(minn)
ans = []
//l = []
for i in range(d):
    m = int(input())
    //l.append(m)
    if m >= maxx:
        ans.append(n)
    elif m < minn:
        ans.append(0)
    elif m == minn:
        ans.append(mi)
    else:
        ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
ans = []
for i in range(d):
    y = 0
    m = int(input())
    for elt in x:
        if m >= elt:
            y+=1;
    ans.append(y)
for elt in ans:
    print(elt)


n = int(input())
x = [int(elt) for elt in input().split(" ")]
d = int(input())
ans = []
for i in range(d):
    m = int(input())
    ans.append(sum(m >= y for y in x))
for elt in ans:
    print(elt)


n = int(input())
x = [int(i) for i in input().split()]
x.sort()
q = int(input())

d = {}
for i in range(q):
	m = int(input())
	if m not in d.keys():
		if m < x[0]:
			d[m] = 0
		elif m >= x[-1]:
			d[m] = n
		else:
			d[m] = next(xi[0] for xi in enumerate(x) if xi[1] > m)
	print(d[m])


n = int(input())
x = [int(i) for i in input().split()]
q = int(input())

d = {}
for i in range(q):
	m = int(input())
	if m not in d.keys():
		d[m] = sum([i<=m for i in x])
	print(d[m])


n = int(input())
x = [int(i) for i in input().split()]
x.sort()
q = int(input())
m = [int(input()) for i in range(q)]
ind = sorted(range(len(m)), key=m.__getitem__)
m.sort()

num = [0] * q
m0 = 0
d = {}
for i in range(q):
	if m[i] not in d.keys():
		if m[i] < x[0]:
			d[m[i]] = m0
		elif m[i] >= x[-1]:
			d[m[i]] = n
		else:
			for j in range(len(x)):
				if x[j] >= m[i]:
					x = x[j:]
					d[m[i]] = m0+j+1
					m0 = j
					break
	num[ind[i]] = str(d[m[i]])

print("\n".join(num))


n = int(input())
x = [int(i) for i in input().split()]
xmin = min(x)
xmax = max(x)
q = int(input())

d = {}
for i in range(q):
	m = int(input())
	if m not in d.keys():
		if m < xmin:
			d[m] = 0
		elif m >=xmax:
			d[m] = n
		else:
			d[m] = sum([i<=m for i in x])
	print(d[m])


n = int(input())
x = [int(i) for i in input().split()]
q = int(input())

for i in range(q):
	m = int(input())
	print(sum([i<=m for i in x]))


from collections import Counter

def binarysearch(x,t):
	left = 0
	right = len(x)
	while left < right:
		middle = (left + right) // 2
		if x[middle][0] <= t:
			left = middle + 1
		else:
			right = middle

	return str(sum([i[1] for i in x[:left]]))

n = int(input())
x = sorted(Counter([int(i) for i in input().split()]).items())
q = int(input())
m = [int(input()) for i in range(q)]

num = [0] * q
for i in range(q):
	if x[0][0] > m[i]:
		num[i] = '0'
	elif x[-1][0] <= m[i]:
		num[i] = str(n)
	else:
		num[i] = binarysearch(x, m[i])

print("\n".join(num))


from collections import Counter

def binarysearch(x,t):
	left = 0
	right = len(x)
	while left < right:
		middle = (left + right) // 2
		if x[middle] <= t:
			left = middle + 1
		else:
			right = middle

	return left

n = int(input())
x = [int(i) for i in input().split()]
x.sort()
q = int(input())
m = [int(input()) for i in range(q)]

num = [0] * q
for i in range(q):
	if x[0] > m[i]:
		num[i] = '0'
	elif x[-1] <= m[i]:
		num[i] = str(n)
	else:
		num[i] = str(binarysearch(x, m[i]))

print("\n".join(num))


from collections import Counter

def binarysearch(x,t):
	left = 0
	right = len(x)
	while left < right:
		middle = (left + right) // 2
		if x[middle] <= t:
			left = middle + 1
		else:
			right = middle
	return left

n = int(input())
x = [int(i) for i in input().split()]
x.sort()
q = int(input())
m = [int(input()) for i in range(q)]

num = [0] * q
for i in range(q):
	if x[0] > m[i]:
		num[i] = '0'
	elif x[-1] <= m[i]:
		num[i] = str(n)
	else:
		num[i] = str(binarysearch(x, m[i]))

print("\n".join(num))


n = int(input())
x = [int(i) for i in input().split()]
x.sort()
q = int(input())
m = [int(input()) for i in range(q)]
ind = sorted(range(len(m)), key=m.__getitem__)
m.sort()

num = [0] * q
m0 = 0
d = {}
for i in range(q):
	if m[i] not in d.keys():
		if m[i] >= x[-1]:
			d[m[i]] = n
		else:
			for j in range(len(x)):
				if x[j] > m[i]:
					x = x[j:]
					d[m[i]] = m0+j
					m0 += j
					break
	num[ind[i]] = str(d[m[i]])

print("\n".join(num))


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n-1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

arr = []
for c in coins:
	num = 0
	l = 0 # index
	r = n # index
	m = n // 2 # index
	while l <= r:
		if c == costs[m]:
			num = m + 1
			break
		elif c < costs[m]:
			r = m - 1
			m = (r + l) // 2

		elif c > costs[m]:
			l = m + 1
			m = (r + l) // 2
	else:
		num = 0
	print(num)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	c += .1
	while l <= r:
		if c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			if m != n - 1 and costs[m+1] == costs[m]:
				key = costs[m] + 0.1
				l = m + 1
				r = n - 1
				m = (l + r) // 2
				while l != r:
					if key == costs[m]:
						break
					if key < costs[m]:
						r = m - 1
					elif key > costs[m]:
						l = m + 1
					m = (l+r) // 2
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n
	m = n // 2
	while l <= r:
		if c == costs[m]:
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			if m != n - 1 and costs[m+1] == costs[m]:
				key = costs[m] + 0.1
				l = m + 1
				r = n - 1
				m = (l + r) // 2
				while l <= r:
					if key == costs[m]:
						break
					if key < costs[m]:
						r = m - 1
					elif key > costs[m]:
						l = m + 1
					m = (l+r) // 2
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			if m != n - 1 and costs[m+1] == costs[m]:
				key = costs[m] + 0.1
				l = m + 1
				r = n - 1
				m = (l + r) // 2
				while l < r:
					if key == costs[m]:
						break
					if key < costs[m]:
						r = m - 1
					elif key > costs[m]:
						l = m + 1
					m = (l+r) // 2
				m -= 1
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			tmp = costs[m]
			cnt = -1
			for i in range(m+1, n):
				if costs[i] == tmp:
					m += 1
				else:
					break

			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			if m != n - 1 and costs[m+1] == costs[m]:
				key = costs[m] + 0.1
				l = m + 1
				r = n - 1
				m = (l + r) // 2
				while l < r:
					if key == costs[m]:
						break
					if key < costs[m]:
						r = m - 1
					elif key > costs[m]:
						l = m + 1
					m = (l+r) // 2
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			if costs[m+1] == costs[m]: # might have to deal with index error
				# need to find upper bound of repeat
				key = costs[m] + 0.1
				l = m + 1
				r = n - 1
				m = (l + r) // 2
				while l != r:
					# print(f"L:{l} R:{r}")
					# print(f"costs[m]: {costs[m]}")
					if key < costs[m]:
						r = m - 1
					elif key > costs[m]:
						l = m + 1
					m = (l+r) // 2
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	l = 0
	r = n - 1
	m = n // 2
	while l <= r:
		if c == costs[m]:
			# print(f"m: {m}")
			if m != n - 1 and costs[m+1] == costs[m]: # might have to deal with index error
				# need to find upper bound of repeat
				key = costs[m] + 0.1
				l = m + 1
				r = n - 1
				m = (l + r) // 2
				while l != r:
					# print(f"L:{l} R:{r}")
					# print(f"costs[m]: {costs[m]}")
					if key < costs[m]:
						r = m - 1
					elif key > costs[m]:
						l = m + 1
					m = (l+r) // 2
			break
		elif c < costs[m]:
			r = m - 1
		elif c > costs[m]:
			l = m + 1
		m = (l+r) // 2
	print(m+1)


import math
n = int(input())
costs = [int(i) for i in input().split()]
q = int(input())
coins = [int(input()) for i in range(q)]

costs.sort()

for c in coins:
	# num = 0
	# l = 0 # index
	# r = n # index
	# m = n // 2 # index
	# while l <= r:
	# 	print(f"\nL:{l}  M:{m}  R:{r}")
	cnt = 0
	for cost in costs:
		if c < cost:
			break
		else:
			cnt += 1

	print(cnt)


n, a, m = int(input()), list(map(int, input().split())), int(input())
x = [0]*(max(a)+1)
for row in a:
    x[row] += 1
for _ in range(m):
    print(sum(x[:int(input())+1]))


n, a, m = int(input()), sorted(list(map(int, input().split()))), int(input())
for _ in range(m):
    x = int(input())
    s = 0
    for row in a:
        if row > x: break
        s+=1
    print(s)


from bisect import *
from sys import stdin
I = stdin.readline
n, a, m = int(I()), sorted(list(map(int, I().split()))), int(I())
for _ in ' '*m: print(bisect_right(a, int(I())))


from itertools import *
n, a, m = int(input()), list(map(int, input().split())), int(input())
for _ in range(m):
    k = int(input())
    print(len([x for x in a if x<=k]))


import bisect as b;i,c=input,int;i();a=sorted(map(c,i().split()))
for _ in ' '*c(i()):print(b.bisect_right(a,c(i())))


from bisect import *
n, a, m = int(input()), sorted(list(map(int, input().split()))), int(input())
for _ in ' '*m: print(bisect_right(a, int(input())))


n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

x.sort()

dp = [0] * (x[-1] + 1)
x_idx = 0
for i in range(1, x[-1] + 1):
    if i >= x[x_idx]:
        dp[i] = dp[i - 1] + 1
        x_idx += 1
    else:
        dp[i] = dp[i - 1]

res = [dp[el] for el in m]
print(" ".join(map(str, res)))


from collections import Counter

n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

counter_x = Counter(x)
unique_x = sorted(list(set(counter_x)))
print(counter_x, unique_x)

dp = [0] * (unique_x[-1] + 1)

x_idx = 0
for i in range(1, unique_x[-1] + 1):
    if i >= unique_x[x_idx]:
        dp[i] = dp[i - 1] + counter_x[unique_x[x_idx]]
    else:
        dp[i] = dp[i - 1]
    x_idx += 1

print(dp)

res = []
for el in m:
    if el > x[-1]:
        res.append(n)  # all the shops
    else:
        res.append(dp[el])
print(" ".join(map(str, res)))


from collections import Counter

n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

x.sort()
counter_x = Counter(x)

dp = [0] * (x[-1] + 1)
x_idx = 0
for i in range(1, x[-1] + 1):
    if i >= x[x_idx]:
        dp[i] = dp[i - 1] + counter_x[x[x_idx]]
        x_idx += 1
    else:
        dp[i] = dp[i - 1]

res = []
for el in m:
    if el > x[-1]:
        res.append(n)  # all the shops
    else:
        res.append(dp[el])
print(" ".join(map(str, res)))


from collections import Counter

n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

counter_x = Counter(x)
unique_x = sorted(list(set(counter_x)))
# print(counter_x, unique_x)

dp = [0] * (unique_x[-1] + 1)

x_idx = 0
for i in range(1, unique_x[-1] + 1):
    if i >= unique_x[x_idx]:
        dp[i] = dp[i - 1] + counter_x[unique_x[x_idx]]
        x_idx += 1
    else:
        dp[i] = dp[i - 1]

# print(dp)

res = []
for el in m:
    if el > x[-1]:
        res.append(n)  # all the shops
    else:
        res.append(dp[el])
print(" ".join(map(str, res)))


n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

x.sort()

dp = [0] * (x[-1] + 1)
x_idx = 0
for i in range(1, x[-1] + 1):
    if i >= x[x_idx]:
        dp[i] = dp[i - 1] + 1
        x_idx += 1
    else:
        dp[i] = dp[i - 1]

res = []
for el in m:
    if el > x[-1]:
        res.append(n)
    else:
        res.append(dp[el])
print(" ".join(map(str, res)))


from collections import Counter

n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

counter_x = Counter(x)
unique_x = sorted(list(set(counter_x)))
# print(counter_x, unique_x)

dp = [0] * (unique_x[-1] + 1)

x_idx = 0
for i in range(1, unique_x[-1] + 1):
    if i >= unique_x[x_idx]:
        dp[i] = dp[i - 1] + counter_x[unique_x[x_idx]]
        x_idx += 1
    else:
        dp[i] = dp[i - 1]

# print(dp)

res = []
for el in m:
    if el > unique_x[-1]:
        res.append(n)  # all the shops
    else:
        res.append(dp[el])
print(" ".join(map(str, res)))

"""

8
1 1 2 2 3 3 4 5
6
1
3
4
5
6
7"""


n = int(input())

x = list(map(int, input().split()))
q = int(input())
m = []
for _ in range(q):
    m.append(int(input()))

x.sort()
res = []
for el in m:
    for i in range(len(x)):
        if el < x[i]:
            res.append(i)
            break
    else:
        res.append(len(x))
print(" ".join(map(str, res)))


def binary_search(lst, n, left, right):
    if left > right:
        return right
    middle = (left + right) // 2
    if n < lst[middle]:
        right = middle - 1
    elif n > lst[middle]:
        left = middle + 1
    else:
        return middle
    return binary_search(lst, n, left, right)
n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
for i in range(q):
    m = int(input())
    print(binary_search(s,m,0,n-1)+1)


import sys
sys.setrecursionlimit(10000)
def binary_search(lst, n, left, right):
    if left > right:
        return right
    middle = (left + right) // 2
    if n < lst[middle]:
        right = middle - 1
    elif n > lst[middle]:
        left = middle + 1
    else:
        return middle
    return binary_search(lst, n, left, right)
def right(lst,x):
    if x == -1:
        return -1
    elif x+1>=n or lst[x]!=lst[x+1]:
        return x
    return right(lst,x+1)
n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
for i in range(q):
    m = int(input())
    print(right(s,binary_search(s,m,0,n-1))+1)


n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
l = [n]*(max(s)+2)
x = 0
for i in range(n):
    for j in range(s[i]):
        l[j]-=1
for i in range(q):
    m = int(input())
    if m > (max(s)):
        print(n)
    else:
        print(l[m])


n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
y = max(s)
l = [n]*(y+2)
x = 0
for i in range(n):
    for j in range(s[i]):
        l[j]-=1
for i in range(q):
    m = int(input())
    if m > y:
        print(n)
    else:
        print(l[m])


def binary_search(lst, n, left, right):
    if left > right:
        return right
    middle = (left + right) // 2
    if n < lst[middle]:
        right = middle - 1
    elif n > lst[middle]:
        left = middle + 1
    else:
        return middle
    return binary_search(lst, n, left, right)
def right(lst,x):
    if x == -1:
        return -1
    elif x+1>=n or lst[x]!=lst[x+1]:
        return x
    return right(lst,x+1)
n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
for i in range(q):
    m = int(input())
    print(right(s,binary_search(s,m,0,n-1))+1)


def binary_search(lst, n, left, right):
    if left > right:
        return right
    middle = (left + right) // 2
    if n < lst[middle]:
        right = middle - 1
    elif n > lst[middle]:
        left = middle + 1
    else:
        return middle
    return binary_search(lst, n, left, right)
def right(lst,x):
    if x+1>=n or lst[x]!=lst[x+1]:
        return x
    return right(lst,x+1)
n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
for i in range(q):
    m = int(input())
    print(right(s,binary_search(s,m,0,n-1))+1)


n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
for i in range(q):
    m = int(input())
    for j in range(n):
        if s[j]>m:
            print(j)
            break
    else:
        print(n)


n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
y = max(s)
l = [0]*(y+2)
x = 0
for i in range(n):
    l[s[i]]+=1
for i in range(q):
    m = int(input())
    if m > y:
        print(n)
    else:
        print(sum(l[:m+1]))


n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
l = [n]*(max(s)+2)
x = 0
for i in range(n):
    for j in range(s[i]):
        l[j]-=1
for i in range(q):
    m = int(input())
    print(l[m])


import sys
sys.setrecursionlimit(10000)
def binary_search(lst, n, left, right):
    if left > right:
        return right
    middle = (left + right) // 2
    if n < lst[middle]:
        right = middle - 1
    elif n > lst[middle]:
        left = middle + 1
    else:
        return middle
    return binary_search(lst, n, left, right)
def right(lst,x):
    if x == -1:
        return -1
    elif x+1>=n or lst[x]!=lst[x+1]:
        return x
    return right(lst,x+1)
n = int(input())
s = [10000]*10000
q = int(input())
s.sort()
for i in range(q):
    m = int(input())
    print(right(s,binary_search(s,m,0,n-1))+1)


n = int(input())
s = list(map(int,input().split()))
q = int(input())
s.sort()
y = max(s)
l = [0]*(y+2)
x = 0
for i in range(n):
    l[s[i]]+=1
for i in range(1,y+2):
    l[i]+=l[i-1]
for i in range(q):
    m = int(input())
    if m > y:
        print(n)
    else:
        print((l[m]))


# Python 3
import bisect

prices = []
n = int(input())

#for price in (int(x) for x in input().split(" ")):
#    bisect.insort(prices, price)

price = [int(x) for x in input().split(" ")]
price.sort()

days = int(input())

#cache = {}
#def check(coin, guess):
#    if coin == 0:
#        return True
#
#    if guess in cache:
#        if cache[guess] <= coin:
#            return True
#
#    if prices[guess-1] <= coin:
#        if guess not in cache or cache[guess] > coin:
#            cache[guess] = coin
#
#        return True
#
#    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    print(bisect.bisect_right(prices, coins))
#    if coins in cache2:
#        print(cache2[coins])
#        continue
#
#    low = 0
#    high = len(prices)
#
#    if not check(coins, low+1):
#        print(low)
#        cache2[coins] = low
#        continue
#
#    if check(coins, high):
#        print(high)
#        cache2[coins] = high
#        continue
#
#    while(low + 1 < high):
#        mid = low + (high - low) // 2
#        if (check(coins, mid)):
#            low = mid
#        else:
#            high = mid
#
#    if not check(coins, high):
#        print(low)
#        cache2[coins] = low
#    else:
#        print(high)
#        cache2[coins] = high


prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    return prices[guess-1] <= price

for _ in range(days):
    coins = int(input())
    low = 0
    high = len(prices) - 1
    while(low+1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    print(low)


# Python 3
import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

cache = {}
def check(coin, guess):
    if coin == 0:
        return True

    if guess in cache:
        if cache[guess] <= coin:
            return True

    if prices[guess-1] <= coin:
        if guess not in cache or cache[guess] > coin:
            cache[guess] = coin

        return True

    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    if coins in cache2:
        print(cache2[coins])
        continue

    low = 0
    high = len(prices)

    if not check(coins, low+1):
        print(low)
        cache2[coins] = low
        continue

    if check(coins, high):
        print(high)
        cache2[coins] = high
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid

    if not check(coins, high):
        print(low)
        cache2[coins] = low
    else:
        print(high)
        cache2[coins] = high


import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    if coin:
        return prices[guess-1] <= coin
    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)

    if check(coins, high):
        print(hgh)
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    if not check(coins, high):
        print(low)
    else:
        print(high)


# Python 3
import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

cache = []
def check(coin, guess):
    if coin == 0:
        return True

    if guess in cache:
        if cache[guess] <= coin:
            return True

    if prices[guess-1] <= coin:
        if guess not in cache or cache[guess] > coin:
            cache[guess] = coin

        return True

    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    if coins in cache2:
        print(cache2[coins])
        continue

    low = 0
    high = len(prices)

    if not check(coins, low+1):
        print(low)
        cache2[coins] = low
        continue

    if check(coins, high):
        print(high)
        cache2[coins] = high
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid

    if not check(coins, high):
        print(low)
        cache2[coins] = low
    else:
        print(high)
        cache2[coins] = high


import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    if coin:
        return prices[guess-1] <= coin
    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)
    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    if not check(coins, high):
        print(low)
    else:
        print(high)


import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

for _ in range(days):
    coins = int(input())

    count = 0
    for i in prices:
        if i > coins:
            break
        count += 1

    print(count)


# Python 3
import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

cache = []
def check(coin, guess):
    if coin == 0:
        return True

    if guess in cache:
        if cache[guess] <= coin:
            return True

    if prices[guess-1] <= coin:
        return True

    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    if coins in cache2:
        print(cache2[coins])
        continue

    low = 0
    high = len(prices)

    if not check(coins, low+1):
        print(low)
        cache2[coins] = low
        continue

    if check(coins, high):
        print(high)
        cache2[coins] = high
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid

    if not check(coins, high):
        print(low)
        cache2[coins] = low
    else:
        print(high)
        cache2[coins] = high


# Python 3
import bisect

prices = []
n = int(input())

#for price in (int(x) for x in input().split(" ")):
#    bisect.insort(prices, price)

prices = [int(x) for x in input().split(" ")]
prices.sort()

days = int(input())

#cache = {}
#def check(coin, guess):
#    if coin == 0:
#        return True
#
#    if guess in cache:
#        if cache[guess] <= coin:
#            return True
#
#    if prices[guess-1] <= coin:
#        if guess not in cache or cache[guess] > coin:
#            cache[guess] = coin
#
#        return True
#
#    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    print(bisect.bisect_right(prices, coins))
#    if coins in cache2:
#        print(cache2[coins])
#        continue
#
#    low = 0
#    high = len(prices)
#
#    if not check(coins, low+1):
#        print(low)
#        cache2[coins] = low
#        continue
#
#    if check(coins, high):
#        print(high)
#        cache2[coins] = high
#        continue
#
#    while(low + 1 < high):
#        mid = low + (high - low) // 2
#        if (check(coins, mid)):
#            low = mid
#        else:
#            high = mid
#
#    if not check(coins, high):
#        print(low)
#        cache2[coins] = low
#    else:
#        print(high)
#        cache2[coins] = high


# Python 3
import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    if coin:
        return prices[guess-1] <= coin
    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)

    if not check(coins, low+1):
        print(low)
        continue

    if check(coins, high):
        print(high)
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    if not check(coins, high):
        print(low)
    else:
        print(high)


# Python 3
import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

cache = {}
def check(coin, guess):
    if coin == 0:
        return True

    if guess in cache:
        if cache[guess] <= coin:
            return True

    if prices[guess-1] <= coin:
        if guess not in cache or cache[guess] > coin:
            cache[guess] = coin

        return True

    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    print(bisect.bisect_right(prices, coins))
#    if coins in cache2:
#        print(cache2[coins])
#        continue
#
#    low = 0
#    high = len(prices)
#
#    if not check(coins, low+1):
#        print(low)
#        cache2[coins] = low
#        continue
#
#    if check(coins, high):
#        print(high)
#        cache2[coins] = high
#        continue
#
#    while(low + 1 < high):
#        mid = low + (high - low) // 2
#        if (check(coins, mid)):
#            low = mid
#        else:
#            high = mid
#
#    if not check(coins, high):
#        print(low)
#        cache2[coins] = low
#    else:
#        print(high)
#        cache2[coins] = high


import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    if coin:
        return prices[guess-1] <= coin
    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)
    while(low + 1 < high):
        mid = low + (high - low) // 2
        print(mid)
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    if not check(coins, high):
        print(low)
    else:
        print(high)


# Python 3
import bisect

prices = []
n = int(input())

#for price in (int(x) for x in input().split(" ")):
#    bisect.insort(prices, price)

price = [int(x) for x in input().split(" ")]
price.sort()

days = int(input())

#        if cache[guess] <= coin:
#            return True
#
#    if prices[guess-1] <= coin:
#        if guess not in cache or cache[guess] > coin:
#            cache[guess] = coin
#
#        return True
#
#    return False

cache2 = {}
for _ in range(days):
    coins = int(input())
    print(bisect.bisect_right(prices, coins))
#    if coins in cache2:
#        print(cache2[coins])
#        continue
#
#    low = 0
#    high = len(prices)
#
#    if not check(coins, low+1):
#        print(low)
#        cache2[coins] = low
#        continue
#
#    if check(coins, high):
#        print(high)
#        cache2[coins] = high
#        continue
#
#    while(low + 1 < high):
#        mid = low + (high - low) // 2
#        if (check(coins, mid)):
#            low = mid
#        else:
#            high = mid
#
#    if not check(coins, high):
#        print(low)
#        cache2[coins] = low
#    else:
#        print(high)
#        cache2[coins] = high


import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    if coin:
        return prices[guess-1] <= coin
    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)

    if check(coins, high):
        print(high)
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    if not check(coins, high):
        print(low)
    else:
        print(high)


import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

def check(coin, guess):
    if coin:
        return prices[guess-1] <= coin
    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)

    if not check(coins, low+1):
        print(low)
        continue

    if check(coins, high):
        print(high)
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid
    if not check(coins, high):
        print(low)
    else:
        print(high


# Python 3
import bisect

prices = []
n = int(input())

for price in (int(x) for x in input().split(" ")):
    bisect.insort(prices, price)

days = int(input())

cache = []
def check(coin, guess):
    if coin == 0:
        return True

    if guess in cache:
        if cache[guess] <= coin:
            return True

    if prices[guess-1] <= coin:
        return True

    return False

for _ in range(days):
    coins = int(input())

    low = 0
    high = len(prices)

    if not check(coins, low+1):
        print(low)
        continue

    if check(coins, high):
        print(high)
        continue

    while(low + 1 < high):
        mid = low + (high - low) // 2
        if (check(coins, mid)):
            low = mid
        else:
            high = mid

    if not check(coins, high):
        print(low)
    else:
        print(high)


shops_amount = int(input())
prices = list(map(int, input().strip().split()))[:shops_amount]
prices.sort()
days_amount = int(input())
wallet = [int(input()) for i in range(days_amount)]

def binary_search(item_list, item):
    idx = 0
    quantity = 0
    for _ in range(len(item)):
        first = 0
        last = len(item_list) - 1
        found = False
        while first <= last and not found:
            mid = (first + last) // 2
            if first >= last:
                if item_list[mid] > item[idx]:
                    quantity = mid
                    found = True
                else:
                    quantity = mid + 1
                    found = True
            elif item_list[mid] == item[idx]:
                quantity += len(item_list[:mid + 1])
                found = True
            else:
                if item_list[mid] > item[idx]:
                    last = mid - 1
                else:
                    first = mid + 1
        if first > last:
            mid = (first + last) // 2
            if mid < 0:
                quantity = 0
                found = True
            elif item_list[mid] > item[idx]:
                quantity = mid
                found = True
            else:
                quantity = mid + 1
                found = True

        print(quantity)
        quantity = 0
        idx += 1

binary_search(prices, wallet)


shops_amount = int(input())
prices = list(map(int, input().strip().split()))[:shops_amount]
prices.sort()
days_amount = int(input())
wallet = [int(input()) for i in range(days_amount)]

def binary_search(item_list, item):
    idx = 0
    quantity = 0
    for _ in item:
        first = 0
        last = len(item_list) - 1
        found = False
        while first <= last and not found:
            mid = (first + last) // 2
            if item_list[mid] == item[idx]:
                quantity += len(item_list[:mid+1])
                found = True
            else:
                if item[idx] < item_list[mid]:
                    last = mid - 1
                else:
                    first = mid + 1
        print(quantity)
        quantity = 0
        idx+=1

binary_search(prices, wallet)


n_shops = input()

old_x_price = list(map(lambda x: int(x), input().split()))
old_x_price.sort()

q_days = int(input())

m_wallet = []
for day in range(q_days):
    wallet = int(input())
    m_wallet.append(wallet)

idx = 0
for pay_day in range(q_days):
    shop_quantity = 0
    x_price = old_x_price[:]
    br = False
    while not br:
        index_price = round(len(x_price) / 2)

        if index_price == 0:
            if x_price[index_price] > m_wallet[idx]:
                shop_quantity = 0
                print(shop_quantity)
                br = True
            elif x_price[index_price] <= m_wallet[idx]:
                shop_quantity += 1
                print(shop_quantity)
                br = True

        elif x_price[index_price] == m_wallet[idx]:
            while x_price[index_price] == m_wallet[idx] and index_price < len(x_price) - 1:
                index_price += 1
            if index_price == len(x_price):
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True
            else:
                shop_quantity += len(x_price) - 1
                print(shop_quantity)
                br = True

        elif x_price[index_price] > m_wallet[idx]:
            x_price = x_price[:index_price]

        elif x_price[index_price] < m_wallet[idx]:
            num = 2

            while x_price[index_price] <= m_wallet[idx] and index_price < len(x_price) - 1:
                index_price += int(index_price / num)
                num += 1

            if index_price == len(x_price) - 1 and x_price[-1] <= m_wallet[idx]:
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True
            else:
                x_price = x_price[:index_price]

    idx += 1


n_shops = input()

x_price = input()
x_price = x_price.split()
x_price = [int(price) for price in x_price]
x_price.sort()

q_days = int(input())

m_wallet = []
for day in range(q_days):
    wallet = int(input())
    m_wallet.append(wallet)

idx = 0
for pay_day in range(q_days):
    shop_quantity = 0
    index_price = round(len(x_price) / 2)
    while x_price[index_price] > m_wallet[idx] and index_price > 1:
        index_price = round(index_price / 2)

    if x_price[index_price] < m_wallet[idx]:
        while x_price[index_price] < m_wallet[idx]:
            index_price += 1

    if x_price[index_price] == m_wallet[idx]:
        while x_price[index_price] == m_wallet[idx] and index_price < len(x_price) - 1:
            index_price += 1
        if index_price == len(x_price) - 1:
            for price in x_price:
                if m_wallet[idx] >= price:
                    shop_quantity += 1
    elif x_price[index_price] > m_wallet[idx]:
        for price in x_price[:index_price]:
            if m_wallet[idx] >= price:
                shop_quantity += 1

    idx += 1
    print(shop_quantity)


n_shops = input()

old_x_price = input()
old_x_price = old_x_price.split()
old_x_price = [int(price) for price in old_x_price]
old_x_price.sort()

q_days = int(input())

m_wallet = []
for day in range(q_days):
    wallet = int(input())
    m_wallet.append(wallet)

idx = 0
for pay_day in range(q_days):
    shop_quantity = 0
    x_price = old_x_price[:]
    br = False
    while not br:
        index_price = round(len(x_price) / 2)

        if index_price == 0:
            if x_price[index_price] > m_wallet[idx]:
                shop_quantity = 0
                print(shop_quantity)
                br = True
            elif x_price[index_price] <= m_wallet[idx]:
                shop_quantity += 1
                print(shop_quantity)
                br = True

        elif x_price[index_price] == m_wallet[idx]:
            while x_price[index_price]==m_wallet[idx]and index_price < len(x_price)-1:
                index_price+=1
            if index_price==len(x_price):
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True
            else:
                shop_quantity += len(x_price)-1
                print(shop_quantity)
                br = True

        elif x_price[index_price] > m_wallet[idx]:
            x_price = x_price[:index_price]

        elif x_price[index_price] < m_wallet[idx]:
            while x_price[index_price] <= m_wallet[idx] and index_price < len(x_price)-1:
                index_price += int(index_price / 2)
            if index_price == len(x_price)-1 and x_price[-1]==m_wallet[idx]:
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True
            else:
                x_price = x_price[:index_price]
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True

    idx += 1


n_shops = input()

old_x_price = list(map(lambda x: int(x), input().split()))
old_x_price.sort()

q_days = int(input())

m_wallet = []
for day in range(q_days):
    wallet = int(input())
    m_wallet.append(wallet)

idx = 0
for pay_day in range(q_days):
    shop_quantity = 0
    x_price = old_x_price[:]
    br = False
    while not br:
        index_price = round(len(x_price) / 2)

        if index_price == 0:
            if x_price[index_price] > m_wallet[idx]:
                shop_quantity = 0
                print(shop_quantity)
                br = True
            elif x_price[index_price] <= m_wallet[idx]:
                shop_quantity += 1
                print(shop_quantity)
                br = True

        elif x_price[index_price] == m_wallet[idx]:
            while x_price[index_price]==m_wallet[idx]and index_price < len(x_price)-1:
                index_price+=1
            if index_price==len(x_price):
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True
            else:
                shop_quantity += len(x_price)-1
                print(shop_quantity)
                br = True

        elif x_price[index_price] > m_wallet[idx]:
            x_price = x_price[:index_price]

        elif x_price[index_price] < m_wallet[idx]:
            while x_price[index_price] <= m_wallet[idx] and index_price < len(x_price)-1:
                index_price += int(index_price / 2)
            if index_price == len(x_price)-1 and x_price[-1]<=m_wallet[idx]:
                shop_quantity += len(x_price)
                print(shop_quantity)
                br = True
            else:
                x_price = x_price[:index_price]

    idx += 1


n_shops = input()

x_price = list(map(lambda x: int(x), input().split()))
x_price.sort()

q_days = int(input())

m_wallet = []
for day in range(q_days):
    wallet = int(input())
    m_wallet.append(wallet)

idx = 0
for pay_day in range(q_days):
    shop_quantity = 0
    found = False
    initial_point = 0
    last_point = len(x_price) - 1
    while not found:
        index_price = (initial_point + last_point) // 2

        if x_price[index_price] > m_wallet[idx]:
            if index_price == 0:
                print(shop_quantity)
                found = True
            else:
                last_point = index_price

        elif x_price[index_price] < m_wallet[idx]:
            if last_point - initial_point == 1 or last_point - initial_point == 0:
                if x_price[last_point] <= m_wallet[idx]:
                    shop_quantity = last_point+1
                elif x_price[last_point] > m_wallet[idx]:
                    shop_quantity = last_point
                print(shop_quantity)
                found = True
            else:
                initial_point = index_price

        elif x_price[index_price] == m_wallet[idx]:
            while x_price[index_price] == m_wallet[idx] and x_price[index_price] < len(x_price) - 1:
                index_price += 1
            if x_price[index_price] > m_wallet[idx]:
                shop_quantity = index_price
                print(shop_quantity)
                found = True
            else:
                shop_quantity = index_price + 1
                print(shop_quantity)
                found = True

    idx += 1


import java.awt.*;
import java.io.*;
import java.util.*;

public class Abc {
    static int n;
    static Point arr[][];
    static char ans[][];
    public static void main(String[] args) throws Exception {
//        Scanner sc = new Scanner(System.in);
        FastReader sc=new FastReader();
        n=sc.nextInt();
        arr=new Point[n][n];
        for (int i=0;i<n;i++) {
            for (int j = 0; j < n; j++) {
                int x=sc.nextInt(),y=sc.nextInt();
                if (x==-1){
                    arr[i][j]=new Point(-1,-1);
                    continue;
                }
                arr[i][j]=new Point(x-1,y-1);
            }
        }
        ans=new char[n][n];
        for (char ar[]:ans){
            Arrays.fill(ar,'-');
        }
        for (int i=0;i<n;i++){
            for (int j=0;j<n;j++){
                if (arr[i][j].equals(new Point(-1,-1))){
                    if (ans[i][j]!='-')continue;
                    boolean f=false;
                    for (int k=0;k<4;k++){
                        int newR=i+dirX[k];
                        int newC=j+dirY[k];
                        if (isValid(newR,newC) && arr[newR][newR].equals(new Point(-1,-1))){
                            f=true;
                            if (!dfs(newR,newC,arr[i][j],i,j,true)){
                                System.out.println("INVALID");
                                return;
                            }
                            break;
                        }
                    }
                    if (!f){
                        System.out.println("INVALID");
                        return;
                    }
                }else {
                    if (!arr[arr[i][j].x][arr[i][j].y].equals(arr[i][j])){
                        System.out.println("INVALID");
                        return;
                    }
                    if (ans[arr[i][j].x][arr[i][j].y]!='-')continue;
                    if (!dfs(arr[i][j].x,arr[i][j].y,arr[i][j],arr[i][j].x,arr[i][j].y,false)){
                        System.out.println("INVALID");
                        return;
                    }
                }
            }
        }
        StringBuilder sb=new StringBuilder();
        sb.append("VALID\n");
        for(int i=0;i<n;i++){
            for (int j=0;j<n;j++){
                sb.append(ans[i][j]);
            }
            sb.append("\n");
        }
        System.out.print(sb);
    }
    static int dirX[]={-1,1,0,0};
    static int dirY[]={0,0,-1,1};
    static char cc[]={'U','D','L','R'};
    static boolean dfs(int r,int c,Point ch,int pr,int pc,boolean cir){
        if (!cir && ans[r][c]!='-'){
            return false;
        }else if (cir && ans[r][c]=='-'){
            if (!arr[r][c].equals(new Point(-1,-1)))return false;
            ans[r][c] = res(r, c, pr, pc);
        }else if (cir && ans[r][c]!='-')return true;
        else if (!cir && ans[r][c]=='-'){
            ans[r][c]=res(r,c,pr,pc);
//            System.out.println(r+" "+c+" "+pr+" "+pc);
        }
        for (int i=0;i<4;i++){
            int newR=r+dirX[i];
            int newC=c+dirY[i];
            if (isValid(newR,newC)){
                if(arr[newR][newC].equals(ch) && (pr!=newR || pc!=newC)){
//                    System.out.println(r+" "+c);
                    if (!dfs(newR,newC,ch,r,c,cir)){
                        return false;
                    }
                }
            }
        }
        return true;
    }
    static char res(int r,int c,int pr,int pc){
        for (int i=0;i<4;i++){
            if (r+dirX[i]==pr && c+dirY[i]==pc){
                return cc[i];
            }
        }
        return 'X';
    }
    static boolean isValid(int r,int c){
        if (r>=0 && r<n && c>=0 && c<n)return true;
        return false;
    }
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            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;
        }
    }
}