#include <bits/stdc++.h>
#define d(x) cout<<'\n'<<#x<<' '<<x;
using namespace std;
int m,h1,h2,x1,x2,a1,a2,y11,y2,t;
bool b1[1000000],b2[1000000];
int i1[1000000],i2[1000000];
int main()
{
fill(i2,i2+1000000,-1);
fill(i1,i1+1000000,-1);
t=1;
cin >> m >> h1 >> a1 >> x1 >> y11 >> h2 >> a2 >> x2 >> y2 ;
i1[h1]=0;
i2[h2]=0;
for(int i=0;i<m;i++)
{
h1=(x1*h1+y11)%m;
if(b1[h1])
break;
i1[h1]=i+1;
}
for(int i=0;i<m;i++)
{
h2=(x2*h2+y2)%m;
if(b2[h2])
break;
i2[h2]=i+1;
}
if(i1[a1]==-1 || i1[a2]==-1){cout<<-1;return 0;}
int xx=m*i1[a1];
int yy=m*i2[a2];
if(i1[a1]!=i2[a2])
cout<<((xx*yy)/__gcd(xx,yy));
else cout<<i1[a1];
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgZCh4KSBjb3V0PDwnXG4nPDwjeDw8JyAnPDx4Owp1c2luZyBuYW1lc3BhY2Ugc3RkOwppbnQgbSxoMSxoMix4MSx4MixhMSxhMix5MTEseTIsdDsKYm9vbCBiMVsxMDAwMDAwXSxiMlsxMDAwMDAwXTsKaW50IGkxWzEwMDAwMDBdLGkyWzEwMDAwMDBdOwppbnQgbWFpbigpCnsKICAgIGZpbGwoaTIsaTIrMTAwMDAwMCwtMSk7CiAgICBmaWxsKGkxLGkxKzEwMDAwMDAsLTEpOwogICAgdD0xOwogICAgY2luID4+IG0gPj4gaDEgPj4gYTEgPj4geDEgPj4geTExID4+IGgyID4+IGEyID4+IHgyID4+IHkyIDsKICAgIGkxW2gxXT0wOwogICAgaTJbaDJdPTA7CiAgICBmb3IoaW50IGk9MDtpPG07aSsrKQogICAgewogICAgICAgIGgxPSh4MSpoMSt5MTEpJW07CiAgICAgICAgaWYoYjFbaDFdKQogICAgICAgICAgICBicmVhazsKICAgICAgICBpMVtoMV09aSsxOwogICAgfQogICAgZm9yKGludCBpPTA7aTxtO2krKykKICAgIHsKICAgICAgICBoMj0oeDIqaDIreTIpJW07CiAgICAgICAgaWYoYjJbaDJdKQogICAgICAgICAgICBicmVhazsKICAgICAgICBpMltoMl09aSsxOwogICAgfQogICAgaWYoaTFbYTFdPT0tMSB8fCBpMVthMl09PS0xKXtjb3V0PDwtMTtyZXR1cm4gMDt9CiAgICBpbnQgeHg9bSppMVthMV07CiAgICBpbnQgeXk9bSppMlthMl07CiAgICBpZihpMVthMV0hPWkyW2EyXSkKICAgIGNvdXQ8PCgoeHgqeXkpL19fZ2NkKHh4LHl5KSk7CiAgICBlbHNlIGNvdXQ8PGkxW2ExXTsKICAgIHJldHVybiAwOwp9