枚举 1..n,跳过 7 的倍数和各位含 7 的数,累加平方和;含 7 判断用逐位取个位,O(n) 直解。
OJ: roj
题目 ID: 1094
难度:入门
标签:入门数学枚举python
创建: 2026-09-29 18:28
更新: 2026-10-05 00:49
题目描述
若正整数能被 21,输出 2336。
思路
枚举
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-07-05 21:47
# update_at: 2026-07-05 21:47
import sys
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data) # 求和上界
# 与 7 无关:不是 7 的倍数,且十进制各位都没有数字 7
print(sum(i * i for i in range(1, n + 1) if i % 7 and '7' not in str(i)))C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 00:48
* update_at: 2026-10-05 00:48
*/
#include <iostream>
using namespace std;
typedef long long ll;
// 判断 x 的十进制表示中是否含有数字 7
bool has_digit_seven(ll x) {
while (x > 0) {
if (x % 10 == 7) {
return true;
}
x /= 10;
}
return false;
}
int main() {
ll n;
cin >> n;
// 与 7 无关:既不是 7 的倍数,十进制各位也没有数字 7
ll answer = 0;
for (ll i = 1; i <= n; i++) {
if (i % 7 != 0 && !has_digit_seven(i)) {
answer += i * i;
}
}
cout << answer << "\n";
return 0;
}