質數檢查器技術實作

深入了解質數檢查器的完整實作,包含平方根優化算法、輸入驗證系統、錯誤處理機制、雙語界面整合和響應式設計

概述

質數檢查器是一個功能強大的數學工具,專為學生、教師和數學愛好者設計,能夠快速且準確地檢測大於1的正整數是否為質數。 本工具採用純前端架構,完全在瀏覽器端運行,零網路傳輸,確保數據的絕對隱私和安全性。 提供平方根優化算法、智能輸入驗證、詳細錯誤提示、雙語界面等專業功能。

🔒 隱私保護承諾

所有數學計算處理都在您的瀏覽器本地進行,數據不會上傳到任何伺服器,確保您的輸入數據完全安全。

技術架構與核心設計

整體架構設計

技術項目 實作方式 設計考量
前端框架 純 JavaScript (ES6+) 零依賴,最小化載入時間
數學算法 平方根優化質數檢測 時間複雜度優化到 O(√n)
輸入驗證 多層次驗證機制 防止無效輸入和惡意數據
錯誤處理 智能錯誤檢測與提示 用戶體驗優化和教育指導
用戶介面 響應式設計 + 雙語系統 跨設備兼容性與國際化

核心類別架構

class PrimeChecker {
    constructor() {
        this.currentLang = 'zh';
        this.translations = {
            zh: { /* 中文翻譯字典 */ },
            en: { /* 英文翻譯字典 */ }
        };
        this.init();
    }
    
    init() {
        this.setupGlobalLanguageListener();
        this.bindElements();
        this.bindEvents();
        this.updateLanguage();
    }
    
    // 主要檢測流程
    checkPrime() {
        try {
            const number = this.validateInput();
            const result = this.isPrime(number);
            
            this.showResult(number, result.isPrime, result.divisor);
        } catch (error) {
            this.handleError(error);
        }
    }
}

關鍵功能實現

1. 平方根優化質數檢測算法

核心算法採用平方根優化,將時間複雜度從 O(n) 優化到 O(√n),大幅提升大數字檢測效率。 特別處理 2 這個唯一的偶數質數,然後只檢測奇數因子。

// 高效能質數檢測算法 - 平方根優化實作
isPrime(n) {
    // 基本情況:2 是唯一的偶數質數
    if (n === 2) return { isPrime: true };
    
    // 偶數檢查:除了 2 以外的偶數都不是質數
    if (n % 2 === 0) return { isPrime: false, divisor: 2 };
    
    // 平方根優化:只需要檢查到 sqrt(n)
    // 因為如果 n = a × b,且 a ≤ b,則 a ≤ √n
    const sqrt = Math.sqrt(n);
    
    // 只檢查奇數因子,從 3 開始,步長為 2
    for (let i = 3; i <= sqrt; i += 2) {
        if (n % i === 0) {
            // 找到因子,返回第一個發現的因子
            return { isPrime: false, divisor: i };
        }
    }
    
    // 沒有找到因子,確認為質數
    return { isPrime: true };
}

2. 智能輸入驗證系統

多層次輸入驗證確保只接受有效的正整數,包括空值檢查、數值格式驗證、範圍限制和整數檢查。 針對不同錯誤類型提供具體的錯誤訊息和教育性指導。

// 完整的輸入驗證流程
checkPrime() {
    const value = this.input.value.trim();
    
    // 第一層:空值檢查
    if (!value) {
        this.showError(this.t('errorEmpty'));
        return;
    }
    
    // 第二層:數值轉換和格式驗證
    const number = parseInt(value);
    
    // 第三層:有效數字檢查
    if (isNaN(number) || number < 2 || number !== parseFloat(value)) {
        this.showError(this.t('errorInvalid'));
        return;
    }
    
    // 第四層:大數字限制 (防止性能問題)
    if (number > 10000000000) {
        this.showError(this.t('errorTooLarge'));
        return;
    }
    
    // 驗證通過,清除錯誤狀態
    this.hideError();
    
    // 執行質數檢測
    const result = this.isPrime(number);
    this.showResult(number, result.isPrime, result.divisor);
}

3. 雙語系統整合

完整的雙語支援系統,包括界面元素翻譯、動態內容切換、語言偏好記憶和全局語言同步。 支援參數化翻譯,讓數字和動態內容能夠正確插入翻譯字串中。

// 完整的雙語系統實作
translations = {
    zh: {
        title: '質數檢查器',
        subtitle: '輸入數字,快速檢查是否為質數',
        inputLabel: '請輸入數字(大於1的正整數)',
        inputPlaceholder: '例如:17',
        checkBtn: '檢查質數',
        clearBtn: '清除',
        errorEmpty: '請輸入數字',
        errorInvalid: '請輸入大於 1 的正整數',
        errorTooLarge: '數字太大,請輸入小於 10,000,000,000 的數字',
        resultPrime: '{number} 是質數!',
        resultNotPrime: '{number} 不是質數',
        resultDetail: '可被 {divisor} 整除'
    },
    en: {
        title: 'Prime Number Checker',
        subtitle: 'Enter a number to check if it\'s prime',
        inputLabel: 'Enter a number (positive integer greater than 1)',
        inputPlaceholder: 'e.g., 17',
        checkBtn: 'Check Prime',
        clearBtn: 'Clear',
        errorEmpty: 'Please enter a number',
        errorInvalid: 'Please enter a positive integer greater than 1',
        errorTooLarge: 'Number is too large, please enter a number less than 10,000,000,000',
        resultPrime: '{number} is a prime number!',
        resultNotPrime: '{number} is not a prime number',
        resultDetail: 'Divisible by {divisor}'
    }
};

// 全局語言監聽器設置
setupGlobalLanguageListener() {
    window.addEventListener('languageChanged', (event) => {
        this.currentLang = event.detail.language;
        this.updateLanguage();
    });
    
    // 初始化時從全局系統獲取語言
    if (window.globalI18n) {
        this.currentLang = window.globalI18n.currentLanguage;
    }
}

// 參數化翻譯函數
t(key, params = {}) {
    let text = this.translations[this.currentLang][key] || key;
    // 替換參數:{number} -> 實際數字
    Object.keys(params).forEach(param => {
        text = text.replace(`{${param}}`, params[param]);
    });
    return text;
}

實作細節

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

📦 核心質數檢查器類別

核心架構:PrimeChecker 類別包含完整的質數檢測功能,包括建構函數初始化、翻譯系統、事件綁定和主要檢測流程。 採用模組化設計,每個功能職責清晰分離。

// 質數檢查器主類別 - 完整實作
class PrimeChecker {
    constructor() {
        // 當前語言設定,預設為中文
        this.currentLang = 'zh';
        
        // 完整的雙語翻譯字典
        this.translations = {
            zh: {
                title: '質數檢查器',
                subtitle: '輸入數字,快速檢查是否為質數',
                inputLabel: '請輸入數字(大於1的正整數)',
                inputPlaceholder: '例如:17',
                checkBtn: '檢查質數',
                clearBtn: '清除',
                info: '什麼是質數?
質數(Prime Number)是指只能被 1 和自己整除的大於 1 的正整數。例如:2, 3, 5, 7, 11, 13... 都是質數。', errorEmpty: '請輸入數字', errorInvalid: '請輸入大於 1 的正整數', errorTooLarge: '數字太大,請輸入小於 10,000,000,000 的數字', resultPrime: '{number} 是質數!', resultNotPrime: '{number} 不是質數', resultDetail: '可被 {divisor} 整除' }, en: { title: 'Prime Number Checker', subtitle: 'Enter a number to check if it\'s prime', inputLabel: 'Enter a number (positive integer greater than 1)', inputPlaceholder: 'e.g., 17', checkBtn: 'Check Prime', clearBtn: 'Clear', info: 'What is a prime number?
A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. For example: 2, 3, 5, 7, 11, 13... are prime numbers.', errorEmpty: 'Please enter a number', errorInvalid: 'Please enter a positive integer greater than 1', errorTooLarge: 'Number is too large, please enter a number less than 10,000,000,000', resultPrime: '{number} is a prime number!', resultNotPrime: '{number} is not a prime number', resultDetail: 'Divisible by {divisor}' } }; // 執行初始化 this.init(); } init() { // 初始化順序很重要:先綁定元素,再綁定事件,最後載入語言 this.bindElements(); this.bindEvents(); this.loadLanguage(); } }

🌐 全域語言系統整合

語言同步機制:與全站語言系統完美整合,監聽 languageChanged 事件,即時響應語言切換。 支援本地語言偏好記憶和全域語言狀態同步。

// 完整的語言系統整合實作
setupGlobalLanguageListener() {
    // 監聽全域語言切換事件
    window.addEventListener('languageChanged', (event) => {
        this.currentLang = event.detail.language;
        this.updateLanguage();
    });
    
    // 初始化時從全局系統獲取當前語言
    if (window.globalI18n) {
        this.currentLang = window.globalI18n.currentLanguage;
    }
}

loadLanguage() {
    // 檢查是否有保存的語言偏好
    const savedLang = localStorage.getItem('primeCheckerLang');
    if (savedLang && this.translations[savedLang]) {
        this.currentLang = savedLang;
    }
    this.updateLanguage();
}

updateLanguage() {
    const t = this.translations[this.currentLang];
    
    // 更新所有帶有 data-i18n 屬性的元素
    document.querySelectorAll('[data-i18n]').forEach(el => {
        const key = el.dataset.i18n;
        if (t[key]) {
            el.innerHTML = t[key];
        }
    });
    
    // 更新placeholder屬性
    document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
        const key = el.dataset.i18nPlaceholder;
        if (t[key]) {
            el.placeholder = t[key];
        }
    });
    
    // 如果有結果顯示,需要重新檢查以更新語言
    if (this.result.style.display !== 'none' && this.input.value) {
        this.checkPrime();
    }
}

// 參數化翻譯函數 - 支援動態參數插入
t(key, params = {}) {
    let text = this.translations[this.currentLang][key] || key;
    // 替換參數:{number} -> 實際數字, {divisor} -> 因子
    Object.keys(params).forEach(param => {
        text = text.replace(`{${param}}`, params[param]);
    });
    return text;
}

🎯 DOM 元素初始化與事件綁定

元素管理:完整的 DOM 元素查詢、緩存和事件綁定。包括輸入框、按鈕、結果顯示區域和錯誤訊息區域的管理。 支援鍵盤快捷鍵(Enter 鍵觸發檢查)和即時輸入反饋。

// DOM 元素綁定和事件處理完整實作
bindElements() {
    // 快取所有重要的 DOM 元素,避免重複查詢
    this.input = document.getElementById('primeInput');
    this.checkBtn = document.getElementById('checkBtn');
    this.clearBtn = document.getElementById('clearBtn');
    this.result = document.getElementById('result');
    this.errorMessage = document.getElementById('errorMessage');
    
    // 驗證元素是否存在,防止 null reference 錯誤
    if (!this.input || !this.checkBtn || !this.clearBtn || !this.result || !this.errorMessage) {
        console.error('Prime Checker: Required DOM elements not found');
        return;
    }
}

bindEvents() {
    // 主要按鈕事件
    this.checkBtn.addEventListener('click', () => this.checkPrime());
    this.clearBtn.addEventListener('click', () => this.clear());
    
    // 鍵盤快捷鍵:Enter 鍵觸發檢查
    this.input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            this.checkPrime();
        }
    });
    
    // 即時輸入反饋:清除錯誤狀態和結果顯示
    this.input.addEventListener('input', () => {
        this.hideError();
        this.hideResult();
    });
    
    // 設置全局語言監聽器
    this.setupGlobalLanguageListener();
}

// 清除功能 - 重置所有狀態
clear() {
    this.input.value = '';
    this.hideError();
    this.hideResult();
    this.input.focus(); // 自動聚焦到輸入框
}

// 錯誤狀態管理
showError(message) {
    this.errorMessage.textContent = message;
    this.errorMessage.style.display = 'block';
    this.input.classList.add('error');
}

hideError() {
    this.errorMessage.style.display = 'none';
    this.input.classList.remove('error');
}

// 結果顯示管理
hideResult() {
    this.result.style.display = 'none';
}

⚙️ 質數檢測演算法引擎

高效能算法:採用平方根優化的質數檢測算法,時間複雜度為 O(√n)。 特殊處理基本情況,只檢查奇數因子,大幅提升大數字檢測效率。返回詳細的檢測結果包括第一個發現的因子。

// 核心質數檢測算法 - 平方根優化實作
isPrime(n) {
    // 特殊情況處理:2 是唯一的偶數質數
    if (n === 2) return { isPrime: true };
    
    // 偶數快速檢查:除了 2 以外的偶數都不是質數
    if (n % 2 === 0) return { isPrime: false, divisor: 2 };
    
    // 平方根優化:只需要檢查到 sqrt(n)
    // 數學原理:如果 n = a × b,且 a ≤ b,則 a ≤ √n
    // 這意味著如果 n 有因子,至少有一個因子 ≤ √n
    const sqrt = Math.sqrt(n);
    
    // 只檢查奇數因子,從 3 開始,步長為 2
    // 因為偶數因子已經在上面檢查過了
    for (let i = 3; i <= sqrt; i += 2) {
        if (n % i === 0) {
            // 找到因子,返回詳細結果
            return { 
                isPrime: false, 
                divisor: i,
                // 可選:包含其他因子 n/i
                otherFactor: n / i
            };
        }
    }
    
    // 沒有找到任何因子,確認為質數
    return { isPrime: true };
}

// 主要檢測流程 - 整合驗證和算法
checkPrime() {
    const value = this.input.value.trim();
    
    // 輸入驗證
    if (!value) {
        this.showError(this.t('errorEmpty'));
        return;
    }
    
    const number = parseInt(value);
    
    // 數值格式和範圍驗證
    if (isNaN(number) || number < 2 || number !== parseFloat(value)) {
        this.showError(this.t('errorInvalid'));
        return;
    }
    
    // 性能限制:防止計算時間過長
    if (number > 10000000000) {
        this.showError(this.t('errorTooLarge'));
        return;
    }
    
    // 清除錯誤狀態
    this.hideError();
    
    // 執行質數檢測算法
    const result = this.isPrime(number);
    
    // 顯示結果
    this.showResult(number, result.isPrime, result.divisor);
}

🎨 結果顯示與用戶介面

視覺化結果:動態生成結果顯示內容,包括圖示、結果文字和詳細說明。 根據結果類型(質數/非質數)自動設定不同的視覺樣式和顏色主題。

// 完整的結果顯示系統
showResult(number, isPrime, divisor) {
    // 動態設定結果容器的 CSS 類別
    this.result.className = `prime-result ${isPrime ? 'is-prime' : 'not-prime'}`;
    
    let html = '';
    
    if (isPrime) {
        // 質數結果顯示
        html = `
            
${this.t('resultPrime', { number })}
只能被 1 和 ${number} 整除
`; } else { // 非質數結果顯示,包含第一個發現的因子 html = `
${this.t('resultNotPrime', { number })}
${this.t('resultDetail', { divisor })}
${number} = ${divisor} × ${number / divisor}
`; } // 更新 DOM 並顯示結果 this.result.innerHTML = html; this.result.style.display = 'block'; // 可選:添加動畫效果 this.result.style.opacity = '0'; setTimeout(() => { this.result.style.opacity = '1'; }, 10); } // CSS 動畫樣式定義(在