GCD & LCM 計算器技術實作

深入了解最大公約數與最小公倍數計算器的完整實作,包含歐幾里得算法優化、輸入驗證系統、錯誤處理機制、結果複製功能和雙語界面整合

概述

GCD & LCM 計算器是一個專為數學教育和實際應用設計的專業計算工具,能夠快速計算兩個正整數的最大公約數(GCD)和最小公倍數(LCM)。 本工具採用經典的歐幾里得算法(輾轉相除法)進行 GCD 計算,並透過數學關係式 LCM(a,b) = (a×b)/GCD(a,b) 計算 LCM。 提供完整的輸入驗證、錯誤處理、結果複製等功能,完全在瀏覽器本地運行,確保計算的準確性和隱私安全。

🧮 歐幾里得算法優勢

使用歐幾里得算法計算 GCD,時間複雜度為 O(log min(a,b)),即使對於大數也能快速計算,是數學史上最古老且最高效的算法之一。

技術架構與核心設計

整體架構設計

技術項目 實作方式 設計考量
算法實現 歐幾里得算法 高效率,O(log min(a,b)) 時間複雜度
輸入驗證 多層次驗證系統 確保輸入為正整數,友好錯誤提示
用戶介面 響應式設計 + 即時反饋 支援各種設備,提升使用體驗
錯誤處理 完整異常捕獲機制 詳細錯誤訊息和視覺標示
國際化 完整雙語系統 支援中英文無縫切換

數學算法基礎

歐幾里得算法 / Euclidean Algorithm:
function gcd(a, b) {
    while (b !== 0) {
        temp = b
        b = a % b
        a = temp
    }
    return a
}

LCM 計算公式 / LCM Calculation Formula:
LCM(a, b) = |a × b| / GCD(a, b)

範例 / Example:
GCD(12, 18):
  12 = 18 × 0 + 12
  18 = 12 × 1 + 6
  12 = 6 × 2 + 0
  → GCD(12, 18) = 6

LCM(12, 18) = 12 × 18 / 6 = 36

關鍵功能實現

  • 🧮 歐幾里得算法:使用經典的輾轉相除法,高效計算最大公約數
  • ⚡ 即時計算:支援 Enter 鍵觸發計算,提供流暢的操作體驗
  • ✅ 完整驗證:檢查空值、數字有效性、整數驗證、正數限制
  • 🎯 錯誤提示:詳細的錯誤訊息和視覺化錯誤標示
  • 📋 結果複製:一鍵複製完整計算結果到剪貼簿
  • 🔄 自動清理:輸入時自動清除錯誤狀態和樣式
  • 🌐 雙語支援:完整的中英文介面和錯誤提示
  • 📱 響應式設計:適配手機、平板、桌面各種設備

⚠️ 數學應用場景

GCD 和 LCM 廣泛應用於分數約簡、時間週期計算、資源分配問題、密碼學等領域,是基礎數學和計算機科學的重要工具。

完整程式碼實作

以下是 GCD & LCM 計算器的完整程式碼實作,按功能模組分類展示。點擊卡片標題可展開查看詳細程式碼:

📦 核心 GCD & LCM 計算器類別

功能:主要的 GCDLCMCalculator 類別,包含建構函數、初始化方法和翻譯系統

/**
 * GCD & LCM Calculator - Core Implementation
 * GCD & LCM 計算器 - 核心實作
 * 
 * A professional tool for calculating Greatest Common Divisor and Least Common Multiple
 * 用於計算最大公約數和最小公倍數的專業工具
 */
class GCDLCMCalculator {
    constructor() {
        // 當前語言設定 / Current language setting
        this.currentLanguage = 'zh';
        
        // 完整的雙語翻譯字典 / Complete bilingual translation dictionary
        this.translations = {
            zh: {
                title: 'GCD & LCM 計算器',
                subtitle: '計算兩個正整數的最大公約數與最小公倍數',
                inputA: '輸入數字 A:',
                inputB: '輸入數字 B:',
                calculate: '🧮 計算',
                clear: '❌ 清除',
                copy: '📋 複製結果',
                gcdLabel: '最大公約數 (GCD):',
                lcmLabel: '最小公倍數 (LCM):',
                formulaLabel: '計算式:',
                algorithmTitle: '🧠 算法說明',
                algorithmDesc: '使用歐幾里得算法計算最大公約數,並通過 LCM(a,b) = (a×b)/GCD(a,b) 公式計算最小公倍數',
                errors: {
                    empty: '請輸入兩個數字',
                    notInteger: '請輸入正整數',
                    notPositive: '僅接受正整數 (>0)',
                    invalid: '請輸入有效數字'
                },
                copied: '結果已複製到剪貼簿!'
            },
            en: {
                title: 'GCD & LCM Calculator',
                subtitle: 'Calculate Greatest Common Divisor and Least Common Multiple of two positive integers',
                inputA: 'Enter Number A:',
                inputB: 'Enter Number B:',
                calculate: '🧮 Calculate',
                clear: '❌ Clear',
                copy: '📋 Copy Result',
                gcdLabel: 'Greatest Common Divisor (GCD):',
                lcmLabel: 'Least Common Multiple (LCM):',
                formulaLabel: 'Formula:',
                algorithmTitle: '🧠 Algorithm',
                algorithmDesc: 'Using Euclidean algorithm for GCD calculation and LCM(a,b) = (a×b)/GCD(a,b) formula for LCM',
                errors: {
                    empty: 'Please enter both numbers',
                    notInteger: 'Please enter positive integers',
                    notPositive: 'Only positive integers allowed (>0)',
                    invalid: 'Please enter valid numbers'
                },
                copied: 'Result copied to clipboard!'
            }
        };
        
        // 初始化工具 / Initialize tool
        this.init();
    }
    
    /**
     * 初始化方法
     * Initialization method
     */
    init() {
        // 設置全域語言監聽器 / Setup global language listener
        this.setupGlobalLanguageListener();
        
        // 設置事件監聽器 / Setup event listeners
        this.setupEventListeners();
        
        // 更新語言顯示 / Update language display
        this.updateLanguage();
    }
}

🌐 全域語言系統整合

功能:整合 Tool Master 全域語言切換系統,支援即時雙語切換

/**
 * 設置全域語言監聽器
 * Setup global language listener
 */
setupGlobalLanguageListener() {
    // 監聽語言切換事件 / Listen for language change events
    window.addEventListener('languageChanged', (event) => {
        this.currentLanguage = event.detail.language;
        this.updateLanguage();
    });
    
    // 檢查全域語言設定 / Check global language setting
    const checkGlobalLanguage = () => {
        if (window.globalI18n) {
            this.currentLanguage = window.globalI18n.currentLanguage;
            this.updateLanguage();
            return true;
        }
        return false;
    };
    
    // 如果全域語言系統尚未載入,延遲檢查 / If global language system not loaded, delay check
    if (!checkGlobalLanguage()) {
        setTimeout(() => {
            checkGlobalLanguage();
        }, 100);
    }
}

/**
 * 更新語言顯示
 * Update language display
 */
updateLanguage() {
    const t = this.translations[this.currentLanguage];
    
    // 更新所有帶有 data-i18n 屬性的元素 / Update all elements with data-i18n attributes
    document.querySelectorAll('[data-i18n]').forEach(element => {
        const key = element.getAttribute('data-i18n');
        if (t[key]) {
            element.textContent = t[key];
        }
    });
    
    // 更新 placeholder 屬性 / Update placeholder attributes
    document.getElementById('numberA').placeholder = this.currentLanguage === 'zh' ? '12' : '12';
    document.getElementById('numberB').placeholder = this.currentLanguage === 'zh' ? '18' : '18';
}

🎯 DOM 事件處理與互動功能

功能:設置所有 DOM 元素的事件監聽器,包含按鈕點擊、鍵盤事件和輸入清理

/**
 * 設置事件監聽器
 * Setup event listeners
 */
setupEventListeners() {
    // 獲取 DOM 元素 / Get DOM elements
    const calculateBtn = document.getElementById('calculateBtn');
    const clearBtn = document.getElementById('clearBtn');
    const copyBtn = document.getElementById('copyBtn');
    const numberA = document.getElementById('numberA');
    const numberB = document.getElementById('numberB');
    
    // 按鈕點擊事件 / Button click events
    calculateBtn.addEventListener('click', () => this.calculate());
    clearBtn.addEventListener('click', () => this.clearInputs());
    copyBtn.addEventListener('click', () => this.copyResults());
    
    // Enter 鍵支援 / Enter key support
    [numberA, numberB].forEach(input => {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.calculate();
            }
        });
    });
    
    // 輸入時清除錯誤狀態 / Clear error state on input
    [numberA, numberB].forEach(input => {
        input.addEventListener('input', () => {
            this.clearError();
            input.classList.remove('error');
        });
    });
}

⚙️ 歐幾里得算法實現

功能:實現經典的歐幾里得算法計算 GCD,並使用數學關係計算 LCM

/**
 * 歐幾里得算法計算最大公約數 (GCD)
 * Euclidean algorithm for calculating Greatest Common Divisor (GCD)
 * 
 * 時間複雜度: O(log min(a, b))
 * Time complexity: O(log min(a, b))
 * 
 * 算法步驟:
 * 1. 如果 b = 0,則 GCD(a, b) = a
 * 2. 否則,GCD(a, b) = GCD(b, a mod b)
 * 3. 重複步驟 2 直到 b = 0
 */
gcd(a, b) {
    // 輾轉相除法 / Division algorithm
    while (b !== 0) {
        let temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

/**
 * 計算最小公倍數 (LCM)
 * Calculate Least Common Multiple (LCM)
 * 
 * 使用數學關係式: LCM(a, b) = |a × b| / GCD(a, b)
 * Using mathematical relationship: LCM(a, b) = |a × b| / GCD(a, b)
 * 
 * 這個公式基於以下數學定理:
 * This formula is based on the mathematical theorem:
 * 對於任意兩個正整數 a 和 b:
 * For any two positive integers a and b:
 * a × b = GCD(a, b) × LCM(a, b)
 */
lcm(a, b) {
    return Math.abs(a * b) / this.gcd(a, b);
}

🎨 輸入驗證與錯誤處理系統

功能:完整的輸入驗證系統,包含空值檢查、數字驗證、整數檢查和正數限制

/**
 * 輸入驗證系統
 * Input validation system
 */
validateInputs() {
    const numberA = document.getElementById('numberA').value.trim();
    const numberB = document.getElementById('numberB').value.trim();
    const t = this.translations[this.currentLanguage];
    
    // 檢查輸入是否為空 / Check if inputs are empty
    if (!numberA || !numberB) {
        return { valid: false, message: t.errors.empty };
    }
    
    // 轉換為數字 / Convert to numbers
    const a = Number(numberA);
    const b = Number(numberB);
    
    // 檢查是否為有效數字 / Check if valid numbers
    if (isNaN(a) || isNaN(b)) {
        return { valid: false, message: t.errors.invalid };
    }
    
    // 檢查是否為整數 / Check if integers
    if (!Number.isInteger(a) || !Number.isInteger(b)) {
        return { valid: false, message: t.errors.notInteger };
    }
    
    // 檢查是否為正數 / Check if positive
    if (a <= 0 || b <= 0) {
        return { valid: false, message: t.errors.notPositive };
    }
    
    return { valid: true, a, b };
}

/**
 * 計算主函數
 * Main calculation function
 */
calculate() {
    // 清除之前的錯誤 / Clear previous errors
    this.clearError();
    
    // 執行輸入驗證 / Perform input validation
    const validation = this.validateInputs();
    
    if (!validation.valid) {
        this.showError(validation.message);
        return;
    }
    
    const { a, b } = validation;
    
    try {
        // 計算 GCD 和 LCM / Calculate GCD and LCM
        const gcdResult = this.gcd(a, b);
        const lcmResult = this.lcm(a, b);
        
        // 顯示結果 / Display results
        this.displayResults(a, b, gcdResult, lcmResult);
        
    } catch (error) {
        this.showError(this.translations[this.currentLanguage].errors.invalid);
    }
}

/**
 * 顯示錯誤訊息
 * Show error message
 */
showError(message) {
    const errorElement = document.getElementById('errorMessage');
    errorElement.textContent = message;
    errorElement.classList.remove('hidden');
    
    // 標記輸入框為錯誤狀態 / Mark inputs as error state
    document.getElementById('numberA').classList.add('error');
    document.getElementById('numberB').classList.add('error');
}

🛠️ 結果顯示與複製功能

功能:結果顯示、複製功能、清除功能和錯誤狀態管理

/**
 * 顯示計算結果
 * Display calculation results
 */
displayResults(a, b, gcd, lcm) {
    // 更新結果顯示 / Update result display
    document.getElementById('gcdResult').textContent = gcd;
    document.getElementById('lcmResult').textContent = lcm;
    document.getElementById('formulaResult').textContent = `GCD(${a},${b}) = ${gcd}, LCM(${a},${b}) = ${lcm}`;
    
    // 顯示結果區域和複製按鈕 / Show result area and copy button
    document.getElementById('resultsSection').classList.remove('hidden');
    document.getElementById('copyBtn').classList.remove('hidden');
}

/**
 * 複製結果到剪貼簿
 * Copy results to clipboard
 */
async copyResults() {
    const gcd = document.getElementById('gcdResult').textContent;
    const lcm = document.getElementById('lcmResult').textContent;
    const formula = document.getElementById('formulaResult').textContent;
    
    // 組合複製文字 / Combine copy text
    const copyText = `${formula}\nGCD: ${gcd}\nLCM: ${lcm}`;
    
    try {
        // 使用 Clipboard API 複製 / Use Clipboard API to copy
        await navigator.clipboard.writeText(copyText);
        
        // 顯示複製成功反饋 / Show copy success feedback
        const originalText = document.getElementById('copyBtn').textContent;
        document.getElementById('copyBtn').textContent = this.translations[this.currentLanguage].copied;
        
        // 2秒後恢復按鈕文字 / Restore button text after 2 seconds
        setTimeout(() => {
            document.getElementById('copyBtn').textContent = originalText;
        }, 2000);
        
    } catch (err) {
        console.error('複製失敗:', err);
    }
}

/**
 * 清除所有輸入和結果
 * Clear all inputs and results
 */
clearInputs() {
    // 清除輸入值 / Clear input values
    document.getElementById('numberA').value = '';
    document.getElementById('numberB').value = '';
    
    // 隱藏結果和複製按鈕 / Hide results and copy button
    document.getElementById('resultsSection').classList.add('hidden');
    document.getElementById('copyBtn').classList.add('hidden');
    
    // 清除錯誤狀態 / Clear error state
    this.clearError();
    
    // 移除輸入框錯誤樣式 / Remove input error styling
    document.getElementById('numberA').classList.remove('error');
    document.getElementById('numberB').classList.remove('error');
}

/**
 * 清除錯誤訊息
 * Clear error message
 */
clearError() {
    document.getElementById('errorMessage').classList.add('hidden');
}

🚀 工具初始化與啟動

功能:工具的啟動程式碼,創建計算器實例並提供功能概述

/**
 * GCD & LCM 計算器初始化
 * GCD & LCM Calculator initialization
 * 
 * 創建計算器實例並開始運行
 * Create calculator instance and start running
 */
new GCDLCMCalculator();

/**
 * 主要功能列表:
 * Main feature list:
 * 
 * 🧮 算法特性 / Algorithm Features:
 * - 歐幾里得算法 GCD 計算 / Euclidean algorithm GCD calculation
 * - 數學關係式 LCM 計算 / Mathematical relationship LCM calculation
 * - O(log min(a,b)) 時間複雜度 / O(log min(a,b)) time complexity
 * 
 * ✅ 驗證功能 / Validation Features:
 * - 空值檢查 / Empty value check
 * - 數字有效性驗證 / Number validity verification
 * - 整數檢查 / Integer check
 * - 正數限制 / Positive number constraint
 * 
 * 🎯 用戶體驗 / User Experience:
 * - Enter 鍵快速計算 / Enter key quick calculation
 * - 即時錯誤清除 / Real-time error clearing
 * - 視覺化錯誤標示 / Visual error indicators
 * - 詳細錯誤訊息 / Detailed error messages
 * 
 * 📋 實用功能 / Utility Features:
 * - 一鍵複製結果 / One-click result copying
 * - 完整結果格式化 / Complete result formatting
 * - 自動清理功能 / Auto cleanup function
 * 
 * 🌐 國際化 / Internationalization:
 * - 完整雙語支援 / Complete bilingual support
 * - 即時語言切換 / Real-time language switching
 * - 本地化錯誤訊息 / Localized error messages
 * 
 * 📱 響應式設計 / Responsive Design:
 * - 手機端適配 / Mobile adaptation
 * - 平板端優化 / Tablet optimization
 * - 桌面端完整功能 / Desktop full functionality
 */

算法分析與效能

時間複雜度分析

  • 歐幾里得算法:時間複雜度 O(log min(a,b)),是計算 GCD 的最高效算法
  • LCM 計算:基於 GCD 結果的 O(1) 計算,整體複雜度不增加
  • 空間複雜度:O(1),只使用常數額外空間
  • 實際性能:即使對於大整數也能在毫秒級完成計算

⚡ 算法優勢

歐幾里得算法是數學史上最古老的算法之一(約西元前 300 年),至今仍是計算 GCD 的最高效方法,體現了數學算法的永恆價值。

安全性考量

  • 🔒 本地處理:所有計算在瀏覽器本地執行,無數據外洩風險
  • 📊 輸入驗證:嚴格的輸入檢查,防止惡意輸入和注入攻擊
  • 🛡️ 錯誤處理:完善的異常捕獲機制,防止程式崩潰
  • ⚠️ 範圍限制:雖無明確上限,但輸入驗證確保只接受合法正整數

瀏覽器兼容性

瀏覽器 最低版本 核心功能
Chrome 66+ ✅ 完整支援
Firefox 63+ ✅ 完整支援
Safari 13.1+ ✅ 完整支援
Edge 79+ ✅ 完整支援

📱 行動裝置支援

支援所有現代行動瀏覽器,包括 iOS Safari 13.1+ 和 Android Chrome 66+。複製功能需要 HTTPS 環境。

未來改進方向

  • 🔄 支援多個數字的 GCD 和 LCM 計算
  • 📊 添加算法執行過程的視覺化展示
  • 📱 開發專屬的移動應用程式
  • 🎯 整合更多數論相關功能(如貝祖恆等式)
  • 📚 添加教育模式,展示計算步驟
  • 🔗 提供 API 介面供其他應用調用

總結

GCD & LCM 計算器展示了如何將經典的數學算法與現代 Web 技術完美結合。 歐幾里得算法的高效性和工具的易用性使其成為數學學習和實際應用的理想選擇。 完善的輸入驗證和錯誤處理確保了工具的穩定性和可靠性。 這個工具不僅適用於學生學習基礎數論,也能滿足開發者和研究人員的實際計算需求。

🎯 核心價值

將千年數學智慧與現代技術結合,為數學教育和實際應用提供高效、準確、易用的計算工具。