You are standing in the supermarket in front of the freezers. You have a very tough task ahead of you: you have to choose what type of ice cream you want for after dinner that evening. After a while, you give up: they are all awesome! Instead, you take your (fair) k-sided die out of your pocket and you decide to let fate decide.
Of course, the number of ice cream choices, n, may not be pre- cisely k, in which case you could not just throw the die once, rolling i, and take the ith ice cream choice. You therefore have to use some algorithm that involves zero or more die throws that results in an ice cream choice with every choice being exactly equally likely. Being a good computer scientist, you know about the accept-reject method, which would let you make such a fair choice.
At that point, you remember that you have a very important
competition to attend that same afternoon. You absolutely cannot afford to be late for that competition. Because of this, you decide you cannot use the accept-reject method, as there may be no bound
Example: For n = 4 and k = 20 one throw is enough.
on the number of die throws needed to ensure a fair result, so you may end up standing there for a long time and miss the competition! Instead, you resolve to find an algorithm that is fair and uses as few dice choices as possible in the worst case.
Given n and k, can you determine the minimum number i such that there is a fair algo- rithm that uses at most i die throws per execution?
Input
On the first line one positive number: the number of test cases, at most 100. After that per test case:
one line with two space-separated integers n and k (1 n, k 109): the number of ice cream choices and the number of sides of your die, respectively.
Output
Per test case:
one line with a single integer: the smallest number of throws after which you are guar- anteed to be able to make a fair choice. If there is no such number, print “unbounded” instead.
Sample in- and output
Input |
Output | |
3 |
|
|
4 |
2 |
2 |
2 |
4 |
1 |
3 |
2 |
unbounded |
题意:有一个k个面的骰子,每个面被摇到的概率相同,有n个雪糕,通过摇骰子选出一个雪糕
问最少摇几次。
当n=1时,次数为0
当n<k时,如果n和k的最大公因数是n,就可以将k平分为n个面,只需摇1次。否则unbounded;
当n>k时,因为可以将k进行划分,所以只需求解k和n的最大公因数即可,然后查看n被骰的剩下几种(即n/gcd(n,k))
直至gcd(n,k)==1,如果最后n==1,则可以选出,否则不行.
#include<stdio.h>
#include<string.h>
int gcd(int a,int b)
{
if(a%b==0)
return b;
return gcd(b,a%b);
}
int main()
{ long long int f,n,k,countt,x;
scanf("%d",&f);
while(f--){
scanf("%d %d",&n,&k);
if(n==1){
printf("0\n");
continue;
}
else if(n<=k&&k%n==0){
printf("1\n");
continue;
}
x=gcd(n,k);
if(x==1){
printf("unbounded\n");
continue;
}
countt=0;
while(x!=1){
n=n/x;
x=gcd(n,k);
countt++;
}
if(n==1)
printf("%d\n",countt);
else
printf("unbounded\n");
}
return 0;
}