#46212: c++ ans


yp11351205@yphs.tp.edu.tw (809-36黃泊霖)

學校 : 臺北市私立延平高級中學
編號 : 276130
來源 : [203.72.178.1]
最後登入時間 :
2025-07-16 13:08:26

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

// 計算兩個數字的最大公因數
int gcd(int a, int b) {
    while (b != 0) {
        a %= b;
        swap(a, b);
    }
    return a;
}

int main() {
    while (true) {
        int N;
        cin >> N;  // 讀取集合的大小
        if (N == 0) break; // 結束條件

        vector<int> numbers(N);
        for (int i = 0; i < N; i++) {
            cin >> numbers[i];  // 讀取集合中的數字
        }

        int totalPairs = 0;  // 總共的數字對數
        int gcdCount = 0;    // 互質的數字對數

        // 優化:減少不必要的計算
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                totalPairs++;
                if (gcd(numbers[i], numbers[j]) == 1) {
                    gcdCount++;
                }
            }
        }

        // 如果沒有任何互質對
        if (gcdCount == 0) {
            cout << "No estimate for this data set." << endl;
        } else {
            // 用公式估算 Pi
            double piEstimate = sqrt(6.0 * totalPairs / gcdCount);
            printf("%.6f\n", piEstimate);  // 輸出 Pi,保留6位小數
        }
    }

    return 0;
}