求一个关于(k*x+b)%c=0的快速算法~
如题~就是求一个(k*x+b)%c=0的快速算法~其中k和b是一个在用户端输入的1e5以内的整型实数,求x的最小值~注意效率要尽可能高的~
[此贴子已经被作者于2017-10-12 01:05编辑过]
[此贴子已经被作者于2017-10-12 01:05编辑过]
#include <stdio.h> #include <math.h> #include <assert.h> // ax + by = c (a!=0) // x = x0 + n*k _Bool gcd3( int a, int b, int c, int* x0, int* k ) { if( a == 0 ) return 0; int A=a, B=b, BX=0, BY=1; while( B ) { BX = (a-B*BX)/A; BY = (b-B*BY)/A; int ta = A; A = B; B = ta%B; } if( c%A != 0 ) return 0; *x0 = c*BY/(a*BY-b*BX); *k = b/A; return 1; } // (k*x+b)%c=0 ---> k*x + -c*y = -b _Bool NineTurnGalaxy( int k, int b, int c, int* px ) { int first, step; _Bool r = gcd3( k, -c, -b, &first, &step ); if( !r ) return r; *px = (first%step + abs(step))%step; return r; } int main( void ) { // (7*x+11)%17=0 int x; _Bool r = NineTurnGalaxy( 7, 11, 17, &x ); assert( r && (7*x+11)%17==0 ); }
[此贴子已经被作者于2017-10-13 04:45编辑过]