Number Transformation

In this problem, you are given an integer number s. You can transform any integer number A to another integer number B by adding x to A. This x is an integer number which is a prime factor of A (please note that 1 and A are not being considered as a factor of A). Now, your task is to find the minimum number of transformations required to transform s to another integer number t.

Input

Input starts with an integer T (≤ 500), denoting the number of test cases.

Each case contains two integers: s (1 ≤ s ≤ 100) and t (1 ≤ t ≤ 1000).

Output

For each case, print the case number and the minimum number of transformations needed. If it's impossible, then print -1.

Sample Input

2

6 12

6 13

Sample Output

Case 1: 2

Case 2: -1

题意:给定两个数 n和m,n可以加上他的素因子变为另一个数,问最少几次这样的变换才能使n变为m

思路:这道题用广搜,需要注意的一点是加的素因子是变换后更新的那个数的素因子,而不是原来那个数的素因子,先给2到1000的所有素数打个表,然后就是平常做的广搜,特别注意,当n和m相等时,直接输出0,代码如下:

#include
#include
#include
using namespace std;
int a,b,flag,ss[1100],book[1100];
void sushu()
{
    memset(ss,0,sizeof(ss));
    for(int i = 2; i<1010; i++)
    {
        if(ss[i] == 0) //0代表素数
        {
            for(int j=i*2; j<1010; j+=i)
                ss[j]=1;//1代表非素数
        }
    }
}
struct node
{
    int x,f;
};
void bfs(int x)
{
    queueQ;
    node q,p;
    q.x=x;
    q.f=0;
    book[x]=1;
    Q.push(q);
    while(!Q.empty())
    {
        p=Q.front();
        Q.pop();
        for(int i=2; ib)
                    continue;
                book[q.x]=1;
                q.f=p.f+1;
                if(q.x==b)
                {
                    flag=q.f;
                    return ;
                }
                Q.push(q);
            }
        }
    }
    return ;
}
int main()
{
    int T,k=1;
    scanf("%d",&T);
    sushu();
    while(T--)
    {
        flag=0;
        memset(book,0,sizeof(book));
        scanf("%d%d",&a,&b);
        if(a==b)
            printf("Case %d: 0\n",k++);
        else
        {
           bfs(a);
        if(flag==0)
            printf("Case %d: -1\n",k++);
        else
            printf("Case %d: %d\n",k++,flag);
        }
    }
    return 0;
}

 

你可能感兴趣的:(Number Transformation)