九度 1465:最简真分数
给出n个正整数,任取两个数分别作为分子和分母组成最简真分数,编程求共有几个这样的组合。
思路
1. 题目考察的是 GCD
代码
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int numbers[700]; int gcd(int x, int y) { if(x == 1 || y == 1) return 1; if(x == y) return x; if(x < y) swap(x, y); if(x&1 == 1) { if(y&1 == 1) return gcd(x-y, y); else return gcd(x, y/2); }else { if(y&1 == 1) return gcd(x/2, y); else return 2*gcd(x/2, y/2); } } int main() { int n; while(scanf("%d", &n) != EOF && n != 0) { for(int i = 0; i < n; i ++) scanf("%d", numbers+i); sort(numbers, numbers + n); int cnt = 0; for(int i = 0; i < n; i ++) { for(int j = i+1; j < n; j ++) if(gcd(numbers[i], numbers[j]) == 1) cnt ++; } cout << cnt << endl; } return 0; }