#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
long long k,l1,r1,l2,r2,y,x,c=0;
cin >> k >> l1 >> r1 >> l2 >> r2;
if(min(r1,r2)>=max(l1,l2))
{
c=min(r1,r2)-max(l1,l2)+1;
}
int p=1;
////
while(pow(k,p)*l1<=1e9)
{
x=l1;
bool b = 0;
int s = pow(k,p);
if(s*l1>r2)
{
break;
}
while(b==0)
{
if(s*x<=r2&&s*x>=l2)
{
y=s*x;
b=1;
}
else
{
x++;
}
}
while(l1<=x&&x<=r1&&l2<=y&&y<=r2)
{
c++;
x++;
y=s*x;
}
p++;
////
}
cout << c << endl;
}
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpCnsKICAgIGludCB0OwogICAgY2luID4+IHQ7CgogICAgd2hpbGUodC0tKQogICAgewogICAgICAgIGxvbmcgbG9uZyBrLGwxLHIxLGwyLHIyLHkseCxjPTA7CiAgICAgICAgY2luID4+IGsgPj4gbDEgPj4gcjEgPj4gbDIgPj4gcjI7CiAgICAgICAgaWYobWluKHIxLHIyKT49bWF4KGwxLGwyKSkKICAgICAgICB7CiAgICAgICAgICAgIGM9bWluKHIxLHIyKS1tYXgobDEsbDIpKzE7CiAgICAgICAgfQogICAgICAgIGludCBwPTE7CgogICAgICAgIC8vLy8KICAgICAgICB3aGlsZShwb3coayxwKSpsMTw9MWU5KQogICAgICAgIHsKICAgICAgICAgICAgeD1sMTsKICAgICAgICAgICAgYm9vbCBiID0gMDsKICAgICAgICAgICAgaW50IHMgPSBwb3coayxwKTsKICAgICAgICAgICAgaWYocypsMT5yMikKICAgICAgICAgICAgewogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgd2hpbGUoYj09MCkKICAgICAgICAgICAgewogICAgICAgICAgICAgICAgaWYocyp4PD1yMiYmcyp4Pj1sMikKICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgICB5PXMqeDsKICAgICAgICAgICAgICAgICAgICBiPTE7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgeCsrOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIAoKICAgICAgICAgICAgd2hpbGUobDE8PXgmJng8PXIxJiZsMjw9eSYmeTw9cjIpCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIGMrKzsKCiAgICAgICAgICAgICAgICB4Kys7CiAgICAgICAgICAgICAgICB5PXMqeDsKICAgICAgICAgICAgfQogICAgICAgICAgICBwKys7CiAgICAgICAgICAgIC8vLy8KICAgICAgICB9CiAgICAgICAgY291dCA8PCBjIDw8IGVuZGw7ICAgIAogICAgfQp9