判斷互質——輾轉相除法

/*
總時間限制: 1000ms 內存限制: 65536kB
描述
給出n個正整數,任取兩個數分別作爲分子和分母組成最簡真分數,編程求共有幾個這樣的組合。

輸入
輸入有多組,每組包含n(n<=600)和n個不同的整數,整數大於1且小於等於1000。
當n=0時,程序結束,不需要處理這組數據。
輸出
每行輸出最簡真分數組合的個數。
樣例輸入
7
3 5 7 9 11 13 15
3 
2 4 5
0
樣例輸出
17 
2
BUG:本題做的時候主要是TLE,關鍵在於原來判斷兩數是否互質的算法爲遍歷
改爲輾轉相除法後就AC了
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
bool isRight(int a,int b)
{
	int t;
	while(b != 0)
	{
		t = a%b;
		a = b;
		b = t;
	}
	if(a == 1)
		return true; 
	return false;
}

int main()
{
	int n;
	int *num;
	int count;
	while(scanf("%d",&n)!= EOF)
	{
		if(n == 0)
			break;
		else
		{
			num = new int[n];
			for(int i = 0; i < n; ++i)
				scanf("%d",&num[i]);
			sort(num,num+n);
			count = 0;
			for(int i = 0; i < n-1; ++i)
			{
				for(int j = i+1; j < n; ++j)
				{
					if(isRight(num[j],num[i]))
						++count;
				}
			}
			printf("%d\n",count); 
			delete [] num;
		}
	}
	system("pause");
	return 0;
}

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