熱門文章

2026年4月13日 星期一

ZeroJudge 解題筆記:d117. 10924 - Prime Words

作者:王一哲
日期:2026年4月13日


ZeroJudge 題目連結:d117. 10924 - Prime Words

解題想法


因為題目的字元編號最大值為 $52$,字串長度最大值為 $20$,因此只要建 $0$ 到 $1040$ 之間的質數表就可以了。需要注意,這題的 $1$ 被當作質數,因為範例測資中的 a 答案為 "It is a prime word."。接下來讀取字串,計算各字元的編號加總,查質數表,輸出對應的答案。

Python 程式碼


使用時間約為 7 ms,記憶體約為 8.4 MB,通過測試。
def solve():
    import sys

    maxn = 1040
    sieve = [True]*(maxn+1)
    sieve[0] = False
    for i in range(2, int(maxn**0.5) + 1):
        if sieve[i]:
            for j in range(i*i, maxn+1, i):
                sieve[j] = False
    
    result = []
    data = sys.stdin.read().split()
    ptr = 0
    while ptr < len(data):
        s = data[ptr]
        ptr += 1
        total = 0
        for c in s:
            if c.isupper():
                total += ord(c) - ord('A') + 27
            elif c.islower():
                total += ord(c) - ord('a') + 1
        result.append("It is a prime word.\n" if sieve[total] else "It is not a prime word.\n")
    sys.stdout.write("".join(result))

if __name__ == "__main__":
    solve()


C++ 程式碼


使用時間約為 1 ms,記憶體約為 3.2 MB,通過測試。
#include <iostream>
#include <vector>
#include <cmath>
#include <cctype>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    const int maxn = 1040;
    vector<bool> sieve (maxn+1, true);
    sieve[0] = false;
    for(int i=2; i<=(int)sqrt(maxn); i++) {
        if (sieve[i]) {
            for(int j=i*i; j<=maxn; j+=i) {
                sieve[j] = false;
            }
        }
    }

    string s;
    while(getline(cin, s)) {
        int total = 0;
        for(char c : s) {
            if (isupper(c)) {
                total += c - 'A' + 27;
            } else if (islower(c)) {
                total += c - 'a' + 1;
            }
        }
        cout << (sieve[total] ? "It is a prime word.\n" : "It is not a prime word.\n");
    }
    return 0;
}


沒有留言:

張貼留言