Time Limit: 2 second(s) | Memory Limit: 32 MB |
There is sequence 1, 12, 123, 1234, ..., 12345678910, ... . Nowyou are given two integersA and B, you have to find the numberof integers fromAth number to Bth (inclusive)number, which are divisible by3.
For example, let A = 3. B = 5. So, the numbers in thesequence are, 123, 1234, 12345. And 123, 12345 are divisible by 3. So, theresult 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 numbersin the sequence betweenAth and Bth whichare divisible by3
Sample Input | Output for Sample Input |
2 3 5 10 110 | Case 1: 2 Case 2: 67 |
和3有关的题很容易想到每个数字和为3的倍数即为3的余数,关键是能不能根据数据推导出第二条规律,,,,,,,,,,,,,,,,
一些数:1, 12, 123, 1234, ..., 12345678910, ... 然后给出两个数A, B,求出第A个数和第B数之间又多少个数能够被3整除。
首先要运用到一个性质:
一个数的数字和相加能被三整除,那么这个数也能被3整除。(1)
然后可以发现:
连续三个整数并排在一起组成的数的数字和必然能被3整除。 规律。。。 ( 2)
最后通过(2)总结出:
1.题目中的第3K个数,必然能被三整除。
2. 题目中的第3K + 1个数,其第2个数字到最末一个数字之和必然能被3整除,再加上第一个数字,也就是1,就不能被3整除了。
3. 题目中的第3K + 2个数,其第3个数字到最末一个数字之和必然能被3整除,再加上第一、二个数字,也就是1 + 2 = 3,也能被3整除。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
int main()
{
int t, ncase=1;
scanf("%d", &t);
while(t--)
{
int l, r;
scanf("%d %d", &l, &r);
int sum;
int l1=l-l%3, r1=r-r%3;
int s1=(l1/3)*2,s2=(r1/3)*2;
if(l%3==2)
{
s1+=1;
}
if(r%3==2)
{
s2+=1;
}
sum=s2-s1;
if(l%3==0||l%3==2)
{
sum+=1;
}
printf("Case %d: %d\n",ncase++, sum);
}
return 0;
}
.