HDU 2504 又见GCD

 

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2504

HDU 2504 又见GCD_第1张图片

 

意思就是,已知gcd(a,c)=b,和a,b,求最小的c,其中c!=b。原以为既然c!=b,那么最小的当然是2b啦,可是提交了发先WA。回头分析发现,不是这么简单,原因在于a可能是c的倍数,比如若a=6b,那么c=2b,3b,4b都不是答案,因为这时候gcd(a,c)=2b,3b,2b。既然如此,只好一个一个试了,从2b开始,一次增加b,直到gcd(a,c)=b。代码如下:

#include using namespace std; int gcd(int a,int b) { while(a%b) { int r=a%b; a=b; b=r; } return b; } int main() { int n,a,b,c,i,j; cin>>n; for (i=0;i>a>>b; c=2*b; while(gcd(a,c)!=b) { c+=b; } cout<

你可能感兴趣的:(编程心得)