ZJANS

q027. 喵-17的倍數

Hard Last Update: 2025/05/16
大數

給一數字 n
判斷此數字是否為 17 的倍數
如果是,輸出 “Yes”
如果不是,輸出離 17 的倍數差多少

※ 題目是離 17 的倍數差多少,要計算最小的差


解法一

🔹 大數取模

利用模運算的性質:
(10a+b)modm=(10(amodm)+b)modm(10a + b)\:\mathbf{mod}\:m = (10(a\:\mathbf{mod}\:m) + b)\:\mathbf{mod}\:m

這代表著數字可以一位一位做取模
此外,為了不一直重複取模浪費時間
res > 1e16 再進行取模

再計算最小的差:min(r, 17-r)

✅ 完整代碼

評分結果(參考) : AC (14ms, 6.7MB)

#include <bits/stdc++.h>
#define int long long
using namespace std;

int mod17(string& num){
    int res = 0;
    
    for(int i=0; i<num.size(); i++){
        res = res*10 + (num[i]-'0');
        if(res > 1e16) res %= 17;
    }
    
    return res % 17;
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string num;
    cin >> num;
    
    int r = mod17(num);
    
    if(r == 0) cout << "Yes";
    else cout << min(r, 17-r);

    return 0;
}
優化

🔹 記憶體優化

一次處理一個字元
避免直接讀入整個字串
減少記憶體開銷

9.1MB → 356KB

🔹 IO 優化

getchar_unlocked()

✅ 完整代碼

評分結果(參考) : AC (8ms, 344KB)

#include <bits/stdc++.h>
#define int long long
using namespace std;

int mod17(){
    int res = 0;

    char c = getchar_unlocked();
    for(; c>='0' && c<='9' && c!=EOF; c=getchar_unlocked()){
        res = res*10 + (c-'0');
        if(res > 1e16) res %= 17;
    }
    
    return res % 17;
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int r = mod17();
    
    if(r == 0) cout << "Yes";
    else cout << min(r, 17-r);

    return 0;
}