1136 - Division by 3
Time Limit: 2 second(s) | Memory Limit: 32 MB |
There is sequence 1, 12, 123, 1234, ..., 12345678910, ... . Now you are given two integers A and B, you have to find the number of integers from Ath number to Bth (inclusive) number, which are divisible by 3.
For example, let A = 3. B = 5. So, the numbers in the sequence are, 123, 1234, 12345. And 123, 12345 are divisible by 3. So, the result is 2.
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case contains two integers A and B (1 ≤ A ≤ B < 231) in a line.
Output
For each case, print the case number and the total numbers in the sequence between Ath and Bth which are divisible by 3.
Sample Input | Output for Sample Input |
2 3 5 10 110 | Case 1: 2 Case 2: 67 |
题意:给出数列如上,求(a,b]区间内能被3整除的项的个数(注意左开右闭);
思路:一个数能被三整除,那么这个数所有数字之和能被3整除,但是貌似在这没用,他给的数列相邻的两项数字和的关系不好找,还是一项一项找规律,3的剩余类为0、1、2,设n%3=0,那么(n+1)%3=1,(n+2)%3=2,设A(n-1)%3=0——>An%3=0,A(n+1)%3=An%3+(n+1)%3=1,A(n+2)%3=A(n+1)%3+(n+2)%3=0,所以对3的余数为010,首项余数是1,那么各项对3的余数为100 100 100.... (其实从第一个算几个数很快就可以发现);
失误:一看题数太大不能打表,连n的速度都不行,只能找到规律,开始一直想将所有数加起来判断,最后虽然发现了规律,但是时间太长了,不如直接算几项,会快很多,一直从理论的方面入手太慢;(后遇到特别大的数,n的复杂度不支持的就推几项试试,反正又花不了多少时间万一找到就节省了大量的;理论推导时间,如果找不到那么就再从理论的方向思考,记住逆向思考主要是换方向,如果还找不到可以先放一放因为这个规律应该很难找)!!!
AC代码:
#include<cstdio>
int main()
{
int T,a,b,Kase=0;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&a,&b);
int ans1=(a-1)/3*2;
int ans2=b/3*2;
if((a-1)%3==2)
{
++ans1;
}
if(b%3==2) ++ans2;
printf("Case %d: %d\n",++Kase,ans2-ans1);
}
return 0;
}