阿摩線上測驗 登入

申論題資訊

試卷:102年 - 102年高等三級暨普通考普通_資訊處理#29218
科目:程式設計
年份:102年
排序:0

題組內容

二、

申論題內容

⑵假設目前陣列 PrimeAry 儲存所有比 n 小的質數,撰寫一函數 PrimeFactor(n)求出 正整數 n 的質因數及其因數次數,並將結果以字串傳回。譬如:PrimeFactor(20)將 回傳字串"2^2 * 5",PrimeFactor(72)將回傳字串"2^3 * 3^2",而 PrimeFactor(97)將 回傳字串"97"。(15 分)

詳解 (共 2 筆)

詳解 提供者:牛奶鍋
string Primefactor(int n) 
{

     string str="";
     int m=n;
     int i, j;
     for(i=2;n>1;i++) //因數
     {   if(n%i) continue;
         for(j=0;n%i==0;j++) //重複有幾次
               n=n/i;
         if(j>1) str=str+to_string(i) +"^"+to_string(j) ; //大於一個才要用^
         else str=str+to_string(i) ;
        if(n>1) str=str+"*"; //還有其他因數
     }
     if(m==n) str=to_string(m); //質數


     return str;
詳解 提供者:hchungw
要求出正整数 n 的所有質因數及其因數次數,我們可以遍歷所有小於等於 n 的質數,並使用之前提到的 FactorTimes 函數來計算每個質數的因數次數。如果質數的因數次數大於0,我們將其加入結果字串中。為了效率,實際上只需遍歷到 sqrt(n) 即可,因為任何大於 sqrt(n) 的因數都不可能成對出現(除非它們是相同的因數,即 n 是某個質數的平方)。
以下是實現 PrimeFactor 函數的程式碼,這裡將使用 Java 語言,並結合之前討論的 FactorTimes 函數:
java
Copy code
public class PrimeFactors {
    // 假設 FactorTimes 函數已被定義
    // 為了完整性,在此提供一個簡單的 FactorTimes 實現
    public static int FactorTimes(int n, int p) {
        if (n % p == 0) {
            return 1 + FactorTimes(n / p, p);
        } else {
            return 0;
        }
    }
    // PrimeFactor 函數求正整數 n 的質因數及其因數次數
    public static String PrimeFactor(int n) {
        StringBuilder result = new StringBuilder();
        
        // 特殊情況處理
        if (n <= 1) {
            return String.valueOf(n);
        }
        
        // 假設 PrimeAry 陣列存在且包含所有需要的質數
        int[] PrimeAry = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; // 示例
        
        for (int p : PrimeAry) {
            if (p * p > n) {
                break;
            }
            int times = FactorTimes(n, p);
            if (times > 0) {
                n /= Math.pow(p, times); // 減少 n 以避免重複計算
                result.append(p).append("^").append(times).append(" * ");
            }
        }
        if (n > 1) { // 如果剩下的 n 是一個質數
            result.append(n);
        } else if (result.length() > 0) { // 移除最後的 " * "
            result.delete(result.length() - 3, result.length());
        }
        
        return result.toString();
    }
    public static void main(String[] args) {
        System.out.println(PrimeFactor(20)); // 應該回傳 "2^2 * 5"
        System.out.println(PrimeFactor(72)); // 應該回傳 "2^3 * 3^2"
        System.out.println(PrimeFactor(97)); // 應該回傳 "97"
    }
}
這段程式碼首先構建了一個 StringBuilder 對象來存儲結果字串。然後,它遍歷一個質數陣列 PrimeAry(這裡假設 PrimeAry 包含了所有小於或等於 n 的質數)。對於陣列中的每個質數 p,它計算 n 包含質數 p 的因數次數。如果次數大於0,則將其格式化後加入結果字串中。