HDU 2504 see GCD again

Source: Internet
Author: User

Question: http://acm.hdu.edu.cn/showproblem.php? Pid = 1, 2504

It means that gcd (a, c) = B, and a, B are known, and the minimum c is obtained, where c! = B. I thought that since c! = B, the minimum is 2b, of course, but WA is submitted first. Looking back, we found that it was not that simple because a may be a multiple of c. For example, if a = 6b, c = 2b, 3b, and 4b are not the answer, because gcd (a, c) = 2b, 3b, 2b at this time. In this case, I had to try it one by one, starting from 2b, increasing B at a time until gcd (a, c) = B. The Code is as follows:

Code

  1 #include <iostream>
2  using namespace std;
3
4 int gcd(int a,int b)
5 {
6 while(a%b)
7 {
8 int r=a%b;
9 a=b;
10 b=r;
11 }
12 return b;
13 }
14
15 int main()
16 {
17 int n,a,b,c,i,j;
18 cin>>n;
19 for (i=0;i<n;i++)
20 {
21 cin>>a>>b;
22 c=2*b;
23 while(gcd(a,c)!=b)
24 {
25 c+=b;
26 }
27 cout<<c<<endl;
28 }
29 return 0;
30 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.