Advertisement
LinKin

Sol of a Diaphantine Eqn

Nov 17th, 2011
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. typedef long long Long;
  2.  
  3. void Egcd( Long a, Long b, Long &x, Long &y, Long &g ){
  4.     if( !b ) x = 1,y = 0,g = a;
  5.     else{
  6.         Long x1,y1;
  7.         Egcd( b,a%b,x1,y1,g );
  8.         x = y1;
  9.         y = x1 - a/b*y1;
  10.     }
  11. }
  12.  
  13. Long MyFloor( Long a, Long b ) {
  14.     Long c = a / b;
  15.     if( (a%b) and a<0 ) c--;
  16.     return c;
  17. }
  18.  
  19. Long Solve( Long a, Long b, Long c, Long x1, Long x2, Long y1, Long y2 ){
  20.     Long x,y,g;
  21.  
  22.     if( a < 0 ) a *= -1, x1 *= -1, x2 *= -1, swap(x1, x2);
  23.     if( b < 0 ) b *= -1, y1 *= -1, y2 *= -1, swap(y1, y2);
  24.  
  25.     if( !a and !b ) return !c ? ( x2-x1+1 )*( y2-y1+1 ) : 0;
  26.     if( b==0 ){
  27.         if( c%a ) return 0;
  28.         x = c/a;
  29.         return ( x>=x1 and x<=x2)*( y2-y1+1 );
  30.     }
  31.     if( a==0 ) {
  32.         if( c%b ) return 0;
  33.         y = c/b;
  34.         return ( y>=y1 and y<=y2 )*( x2-x1+1 );
  35.     }
  36.  
  37.     Egcd( a,b,x,y,g );
  38.     if( c%g ) return 0;
  39.  
  40.     a /= g; b /= g; c /= g; g = 1;
  41.     x = x*c; y = y*c;
  42.  
  43.     Long n2 = min( MyFloor( x-x1, b ), MyFloor( y2-y, a ) );
  44.     Long n1 = -min( MyFloor( y-y1, a ), MyFloor( x2-x, b ) );
  45.     return ( n2<n1 ) ? 0 : n2-n1+1;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement