http://acm.nefu.edu.cn/test/problemshow.php?problem_id=84
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<iomanip>
using namespace std;
typedef long long INT ;
INT gcd( INT a , INT b )
{
return b == 0 ? a : gcd( b , a % b ) ;
}
INT ex_gcd( INT a , INT b , INT &x ,INT &y )
{
if ( b == 0 )
{
x = 1 ;
y = 0 ;
return a ;
}
else
{
INT tm = ex_gcd( b , a % b , x , y ) ;
INT t = x ;
x = y ;
y = t - ( a / b ) * y ;
return tm ;
}
}
int main()
{
INT Case , r , n , s , t , d , x , y , g , res;
scanf( "%lld" , &Case );
while( Case-- )
{
scanf( "%lld%lld%lld%lld" ,&n , &d , &x , &y ) ;
g = gcd( d , n ) ;
x = ( y - x + n ) % n ;
if( x % g != 0 )
{
printf( "Impossible\n" ) ;
continue ;
}
n /= g ;
d /= g ;
r = ex_gcd( d , n , s , t ) ;
if( s < 0 )
s += n ;
res = ( s * x / g ) % n ;
printf( "%lld\n" , res ) ;
}
return 0 ;
}