返回首页 C++ 模板

求余模板

取余运算的原理与常见应用:取个位、判断整除、周期问题

求余 取余 模运算 整除 周期 GESP1
#include <bits/stdc++.h>
using namespace std;

int main() {
    cout << 17 % 5 << endl;   // 2
    cout << 20 % 4 << endl;   // 0(整除)

    // 取个位、十位、百位
    int n = 12345;
    cout << n % 10 << endl;       // 个位 5
    cout << n / 10 % 10 << endl;  // 十位 4

    // 判断整除
    if (n % 3 == 0) cout << "3的倍数" << endl;

    // 奇偶判断
    if (n % 2 == 0) cout << "偶数" << endl;

    // 周期问题:今天周三(3),n天后周几?
    int today = 3, days;
    cin >> days;
    cout << (today + days) % 7 << endl;

    // 循环索引:5人轮流,第i次轮到谁
    for (int i = 1; i <= 12; i++)
        cout << (i - 1) % 5 + 1 << " ";
    cout << endl;

    // 大数取余防溢出
    long long a = 1e9, b = 1e9;
    int mod = 1e9 + 7;
    cout << (a % mod) * (b % mod) % mod << endl;

    return 0;
}

📖 要点说明

⚠️ 常见错误