求余模板
取余运算的原理与常见应用:取个位、判断整除、周期问题
求余
取余
模运算
整除
周期
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;
}
📖 要点说明
a % b结果范围[0, b-1](a,b为正时)- 取余只能用于整数
- 周期问题核心:
(当前位置 + 偏移) % 周期 - 大数取余分配律防溢出
⚠️ 常见错误
- 负数取余需
((n%k)+k)%k保证非负 - 除零会运行时错误
- 循环从1开始:
(i-1)%n+1,不是i%n