题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3629
题目描述:
问某个区间内这样的数 n 有几个,n 满足:
[n/1] +[n/2] + ... + [n/n] + ... is even. (这个除法是向下取整保留整数的)
解题思路:
遇到这种题,看数据量就知道一定是有规律的,不妨写个程序来找规律,用朴素的算法写个程序输出100以内符合要求的数:
0, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 24, ......
观察发现它们是一片一片连着的数,写在纸上,就找出了这样的规律:
(0^2)0 —— 0(1^2 - 1)
(2^2)4 —— 8(3^2 - 1)
(4^2)16 —— 24(5^2 - 1)
(6^2)36 —— 48(7^2 - 1)
........
接下来根据规律,拿等差数列求和公式什么的写出个代码来就行了
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef unsigned long long ll;
ll solve (ll n)
{
if(n==-1) return 0;
ll a = sqrt(n);
ll t;
if(a%2==0)
{
t=(a+1)*(a+1)-a*a;
t=( (1+t) * ((t-1)/4 + 1) ) /2;
t-= (a+1)*(a+1) -1 -n;
}
else
{
t = a*a-(a-1)*(a-1);
t=( (1+t) * ((t-1)/4 + 1) ) /2;
}
return t;
}
int main()
{
//freopen("input.txt","r",stdin);
ll a,b;
//for(int i=0;i<=100;i++)
// cout<<solve(i)<<endl;
while(cin>>a>>b)
cout<<solve(b)-solve(a-1)<<endl;
return 0;
}
AC截图: