求是否存在两个非负系数x,y,使得ax+by=c。a,b属于[1,100],c属于[1,10000]。
数据范围小啊,直接暴力枚举x或者枚举y就行。
数学方法的话应该是扩展欧几里德求不定方程,正好刚看了这个,就当复习了
代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <algorithm> #include <map> using namespace std; int gcd(int a, int b)//普通方法 { int m, n, r; m = a >= b ? a : b;//m>=n n = a<b ? a : b; r = m%n; while (r != 0) { m = n; n = r; r = m%n; } return n; } int ex_gcd(int a, int b, int &x, int &y) { int tmp, ans; if (b == 0) { x = 1; y = 0; return a; } ans = ex_gcd(b, a%b, x, y); tmp = x; x = y; y = tmp - (a / b)*y; return ans; } int main() { int a, b, c, d, p = 0, q = 0; bool ans = 0; scanf("%d%d%d", &a, &b, &c); d = gcd(a, b); if (c%d == 0) { ex_gcd(a, b, p, q); p *= (c / d); q *= (c / d); //printf("gcd %d %d %d\n", d, p, q); if (p < 0) { int t = (-p - 1) / (b / d) + 1; if ((q - (a / d)*t) >= 0) ans = 1; } else if (q < 0) { int t = (-q - 1) / (a / d) + 1; if ((p - (b / d)*t) >= 0) ans = 1; } else ans = 1; } if (ans) printf("Yes\n"); else printf("No\n"); //while (1); return 0; }