代码改变世界

UESTC oj Division by 3 数论

2012-05-19 11:27  javaspring  阅读(247)  评论(0编辑  收藏  举报

      这是群赛上的一道题目,是道数论题。题意比较简单,就是给你一种这样的数,1,12,123,1234,12345,123456.。。。。。。求第a个这样的数到第b个这样的数之间,有多少个数能被3整除。思路很简单,第n个数能否被3整除,只需要从1一直加到n即可。注意,这里的加,是指把某个数的每一位加起来,这是根据一个数能否被3整除的性质所决定的。但是若要循环的话,由于数据范围太大,会超时。

    我刚开始把前100项能被3整除的个数打表打出来后,发现规律很明显,之后就1A了。规律是这样的,能被3整除的个数是这样分布的,0,1,2,2,3,4,4,5,6,6,7,8,8.。。。。。。即奇数出现一次,偶数出现两次,,我们可以以3为周期,接下来就很简单了。题目:

Description

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

2

3 5

10 110

Sample Output

Case 1: 2

Case 2: 67

ac代码:

#include <iostream>
#include <cstdio>
#include <string.h>

using namespace std;

int fun(int x)
{
    int a = x/3;
    int b = 2*a;
    if(x%3 == 2)
    {
        b+=1;
    }
    return b;
}
int main()
{
    int numcase;
    scanf("%d",&numcase);
    for(int k = 1;k <= numcase;++k)
    {
        int m,n,s = 0,e = 0;
        scanf("%d%d",&m,&n);
        if(m == 1 || m == 2) s = 0;
        if(n == 1) e = 0;
        else if(n == 2) e = 1;
        else
        {
            s = fun(m-1);
            e = fun(n);
        }
        printf("Case %d: ",k);
        printf("%d\n",e-s);
    }
    return 0;
}