HDU 2.1.4 又見GCD

又見GCD

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2573 Accepted Submission(s): 1273
 
Problem Description
有三個正整數a,b,c(0<a,b,c<10^6),其中c不等於b。若a和c的最大公約數爲b,現已知a和b,求滿足條件的最小的c。
 
Input
第一行輸入一個n,表示有n組測試數據,接下來的n行,每行輸入兩個正整數a,b。
 
Output
輸出對應的c,每組測試數據佔一行。
 
Sample Input
2
6 2
12 4
 
Sample Output
4
8
 


思路:  

a=i*b   b=b  c=j*b

找到最小的j,使得j和i沒出了1之外的公約數就可以


菜鳥級的原創代碼,已AC。若有可提高之處歡迎指導

#include<stdio.h>
#include<math.h>
int hasCommonFactor(int x,int y)
{
	int s =x > y ? y : x;
	for (int i = 2; i <= s;i++)
	if (x%i + y%i == 0)
		return true;
	return false;
}
int another(int a, int b)
{
	int k = a / b,i=1;
	while(i++)
	if (!hasCommonFactor(k, i))
		return i*b;


}
int main()
{
	int n, a, b;
	scanf("%d", &n);
	while (n--)
	{
		scanf("%d %d", &a, &b);
		printf("%d\n", another(a, b));
	}
	return 0;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章