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
题意·:
给出两个数s,t,s通过加自己的质因子看是否能够等于T.,若能得到,就输出最少的相加次数,若不能输出-1.
思路:
先求每个数的质因子,再通过bfs求最小次数
代码:
#include<stdio.h>
#include<queue>
using namespace std;
#include<string.h>
int c[1110],book[1110];
int a,b,n;
struct node
{
int x,s;
};
int prime(int n)
{
if(n<2)return 0;
for(int i=2; i<n; i++)
{
if(n%i==0)return 0;
}
return 1;
}
void bfs(int x)
{
queue<node>Q;
node p,q;
p.x=x;
p.s=0;
book[x]=1;//标记用过的数字防止循环
Q.push(p);
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(p.x==b)
{
n=p.s;
break;//找到后跳出循环,
}
for(int i=2; i<p.x; i++)//新的数在其范围内找质因数! ,
{ //并且判断是否大于t,或者加上质因数后得到一个用过的数
if(c[i]==0||p.x+i>b||p.x%i!=0||book[p.x+i])continue;
q.x=p.x+i;
book[q.x]=1;
q.s=p.s+1;
Q.push(q);
}
}
return;
}
int main()
{
int k=1;
for(int i=2; i<=1005; i++)
{
c[i]=prime(i);
}
int t;
scanf("%d",&t);
while(t--)
{
n=-1;
memset(book,0,sizeof(book));
scanf("%d%d",&a,&b);
bfs(a);
printf("Case %d: %d\n",k++,n);
}
return 0;
}