7-2 幼儿园数学题(29 分)

我系渣渣辉,我在梦工厂等你,是兄弟就来砍我啊!!

刚上幼儿园的渣渣辉迷上了一款名叫贪玩蓝月的新游戏,由于过于沉迷游戏,上课听讲的效率直线下降。

今天,他的数学老师给他布置了一道求解二元一次方程组的题目,贪玩的他只记下的方程组的一个等式

ax+by=c,他知道一个二元方程是无法求出正确答案的,于是决定在满足此方程且x,y均为非负整数的前提下,

随机选一组x,y作为最后的答案,请聪明的你帮渣渣辉小朋友找出所有的满足条件的x,y组合个数。

输入格式:

输入只有一行,一行3个数字a,b,c(1<=a,b,c<=10000000)

输出格式:

输出只有一行,满足条件的x,y组合个数ans。

输入样例:

在这里给出一组输入。例如:

2 3 16

输出样例:

在这里给出相应的输出。例如:

3
一开始想用暴力,后来超时,然后改为二分查找,还是超时,后来发现,第二个for循环可以直接用一个if代替。

First Try:
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 #include <string.h>
 5 #include <math.h>
 6 #include <map>
 7 #include <queue>
 8 #include <stack>
 9 typedef long long ll;
10 using namespace std;
11 int counts= 0;
12 void secondSearch(int c, int have, int x, int b) {
13     int low = 0;
14     int hei = x;
15     int mid = (hei+low)/2;
16     while(low<hei) {
17         mid = (hei+low)/2;
18         if(mid*b+have == c) {
19             counts++;
20             break;
21         } else if(mid*b+have > c) {
22             hei = mid-1;
23             continue;
24         } else if(mid*b+have < c){
25             low = mid+1;
26             continue;
27         }
28     }
29 }
30 int main()
31 {
32     int a, b, c,min;
33     cin >> a >> b >>c;
34     if(a<b) {
35         min = a;
36     } else {
37         min = b;
38     }
39     int length = c/min;
40 
41     for(int i = 0 ;i <=length;i++) {
42         int x = (c-a*i)/b+1;
43         int sum = c-a*i;
44         
45         secondSearch(c, a*i, x, b);
46         
47 //        for(int j = 0; j<=x;j++) {
48 //            if(a*i+b*j==c) {
49 //                counts++;
50 //            }
51 //        }
52     }
53     cout << counts;
54 }

AC代码:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 #include <string.h>
 5 #include <math.h>
 6 #include <map>
 7 #include <queue>
 8 #include <stack>
 9 typedef long long ll;
10 using namespace std;
11 int main()
12 {
13     int a, b, c;
14     cin >> a >> b >> c;
15     int x=0, cnt=0;
16     while(a*x<=c){
17         if(((c-(a*x))%b)==0)cnt++;
18         x++;    
19     }
20     cout << cnt << endl;
21     return 0;
22 }
原文地址:https://www.cnblogs.com/wzy-blogs/p/9223800.html