♬ Caloventor tiene miedo... ♬
Benedetto, Nathan
As is well known by any cultured person, rats are the smartest beings on earth. Followed directly by dolphins.
MaratonIME knows about the species hierarchy and uses this knowledge in it's regard. Usually, when they need some resource, they know it's always useful to have a smart rat available. Unfortunately, rats are not very fond of us, primates, and will only help us if they owe us some favour.
With that in mind, MaratonIME decided to help a little rat called Pablito. Pablito is studying rat's genealogy, to help with cloning and genetic mapping. luckily, the way rats identify themselves make the job much easier.
The rat society is, historically, matriarchal. At first, there were little families, each of which had it's own leading matriarch. At that time, it was decided that rats would organize themselves according to the following rules:
- Each martiarch had an id number greater than one.
- Each of these ids were chosen in a way such that they would have the least amount of divisors possible.
- Each family member had the same id as the matriarch.
- The id of any newborn rat would be the product of its parents id's.
For instance, the offspring of a rat with id 6 and another with id 7 is 42.
Pablito needs to know if two given rats have a common ancestor, but his only tool is the id number of each of the two rats, which is always a positive integer greater than 1 with no more than 16 digits. Can you help him?
Create a program that decides if a pair of rats have some common ancestor.
Input
The input begins with a positive integer t ≤ 105, the number of test cases.
After that, follows t lines, each with two integers ai e bi identifying two rats.
Every rat's id is a positive integer greater than 1 and with no more than 16 digits.
Output
For each test case, print "Sim" if the rats ai and bi share a common ancestor and "Nao" otherwise.
Example
Input
2
2 4
3 5
Output
Sim
Nao
题意概括:
例子:6*7=42;所以说 6 和 7 是 42 的祖先,测试数据,2 和 4 有公约数2,所以有共同祖先;3 和 5没有除了 1 的公约数 所以没有共同的祖先。其实这道题简而言之,求两个数之间是否有公约数 ,有便输出Sim ,没有便输出Nao。求最大公约数用辗转相除法。
先简单记录一下我之前的错误做法。想着两个数进行先进行排序,求出那个较小的数,然后从2开始遍历,循环(for(i=2;i<=min;i++) , 用 if(id1%i==0&&id2%i==0)判断,如果判断到一个就结束,但是这个方法对于比较大的数还没有公约数的两个数,要遍历到最小的那个数为止,这个方法,对于很大的数,并不能适用,超时。
正确做法:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
long long int i,id1,id2,min;
scanf("%d",&n);
while(n--)
{
int f=0;
long long int z;
scanf("%lld %lld",&id1,&id2);
if(id1>id2)
{
min=id1;
id1=id2;
id2=min;
}
z=0;
if(id2/id1==0)
{
printf("Sim\n");
}
else
{
while(id2%id1!=0)//辗转相除法求最大公约数
{
z=id2%id1;
id2=id1;
id1=z;
}
if(z==1)printf("Nao\n");
else
printf("Sim\n");
}
}
return 0;
}