51Nod-1082 与7无关的数【进制+打表】
基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
一个正整数,如果它能被7整除,或者它的十进制表示法中某个位数上的数字为7,则称其为与7相关的数。求所有小于等于N的与7无关的正整数的平方和。
例如:N = 8,<= 8与7无关的数包括:1 2 3 4 5 6 8,平方和为:155。
Input
第1行:一个数T,表示后面用作输入测试的数的数量。(1 <= T <= 1000) 第2 - T + 1行:每行1个数N。(1 <= N <= 10^6)
Output
共T行,每行一个数,对应T个测试的计算结果。
Input示例
5 4 5 6 7 8
Output示例
30 55 91 91 155
问题链接:1082 与7无关的数
问题分析:计算并不困难,需要考虑怎么避免重复计算,打表是解决办法。
程序说明:程序中,函数check7()用于判断一个数中是否含有数字7。
需要注意计算时不要溢出,程序中的强制类型转换是必要的。
题记:(略)
AC的C++程序如下:
#include <iostream>
#include <cstring>
using namespace std;
const int BASE10 = 10;
const int N = 1e6;
long long ans[N+1];
bool check7(int n)
{
while(n) {
if(n % BASE10 == 7)
return true;
n /= BASE10;
}
return false;
}
void init_ans(int n)
{
for(int i=1; i<=n; i++) {
ans[i] = ans[i - 1];
if(i % 7 == 0 || check7(i))
;
else
ans[i] += (long long)i * i;
}
}
int main()
{
memset(ans, 0, sizeof(ans));
init_ans(N);
int t, n;
cin >> t;
while(t--) {
cin >> n;
cout << ans[n] << endl;
}
return 0;
}
浙公网安备 33010602011771号