A. Choosing Ice Cream(快速幂题)

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) kk-sided die out of your pocket and you decide to let fate decide.

Of course, the number of ice cream choices, nn, may not be precisely kk, in which case you could not just throw the die once, rolling ii, and take the iith 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 importantcompetition 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 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 nn and kk, can you determine the minimum number ii such that there is a fair algorithm that uses at most ii die throws per execution?

Input Format

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 nn and kk (1 \leq n, k \leq 10^91n,k109): the number of ice cream choices and the number of sides of your die, respectively.

Output Format

Per test case:

  • one line with a single integer: the smallest number of throws after which you are guaranteed to be able to make a fair choice. If there is no such number, print “unbounded” instead.

样例输入

3
4 2
2 4
3 2

样例输出

2
1
unbounded

题目来源

BAPC 2014 Preliminary


原理:k^x%n==0

投一次有k种情况,两次就k^2种情况,刚刚好凑成n种情况

#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
int powermod(long long base,int x,long long p)
{
    long long ans=1%p;//考虑到n==1的特殊性
    while(x>0)
	{
       if((x&1)==1)
       ans=(ans*base)%p;     //if里的条件也可以写成x&1
	   base=base*base%p;
	   x=x>>1;
	}
    return ans;
}
int main()
{
    int t;
    int flag;
    scanf("%d",&t);
    while(t--)
    {
      flag=0;
      long long n,k;
      scanf("%lld%lld",&n,&k);
      int i,j;
      i=0;
      for(j=1;j<=n;j*=2)  //变相的sqrt(n),但这个可以处理long long 型的变量,sqrt()用来算int double 型这种小的数
      {                   //因为最多就2*x==n,x次
         if(powermod(k,i,n)==0)
         {
             printf("%d\n",i);
             flag=1;
             break;
         }
         i++;
      }
      if(flag==0)
      printf("unbounded\n");
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/xigongdali/article/details/80983736
ice