【思维/快速幂】PUPU

There is an island called PiLiPaLa.In the island there is a wild animal living in it, and you can call them PuPu. PuPu is a kind of special animal, infant PuPus play under the sunshine, and adult PuPus hunt near the seaside. They fell happy every day.

But there is a question, when does an infant PuPu become an adult PuPu?
Aha, we already said, PuPu is a special animal. There are several skins wraping PuPu's body, and PuPu's skins are special also, they have two states, clarity and opacity. The opacity skin will become clarity skin if it absorbs sunlight a whole day, and sunshine can pass through the clarity skin and shine the inside skin; The clarity skin will become opacity, if it absorbs sunlight a whole day, and opacity skin will keep sunshine out.

when an infant PuPu was born, all of its skins were opacity, and since the day that all of a PuPu's skins has been changed from opacity to clarity, PuPu is an adult PuPu.

For example, a PuPu who has only 3 skins will become an adult PuPu after it born 5 days(What a pity! The little guy will sustain the pressure from life only 5 days old)

Now give you the number of skins belongs to a new-laid PuPu, tell me how many days later it will become an adult PuPu?

InputThere are many testcase, each testcase only contains one integer N, the number of skins, process until N equals 0OutputMaybe an infant PuPu with 20 skins need a million days to become an adult PuPu, so you should output the result mod N

Sample Input

2
3
0

Sample Output

1
2

分析:被照过后状态变化,隔离出n-1层,当照到第n层时结束,即分析前n-1层全通光的情况,在纸上手动模拟一下,可以发现和2的幂次有关,公式为 [latex]ans=2^{n-1}+1[/latex] 之后快速幂搞定。

详细分析请挪歩:小黑贱胖子的题解

AC代码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;
ll pow(ll x, ll n, ll mod)
{
  ll res = 1;
  while (n > 0)
  {
    if (n % 2 == 1)
    {
      res = res * x;
      res = res % mod;
    }
    x = x * x;
    x = x % mod;
    n >>= 1;
  }
  return res;
}

int main()
{
  ll n=0;
  while (cin>>n && n)
  {
    cout << pow(2, n - 1, n) + 1 << endl;;
  }
  return 0;
}

 

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注

19 + 6 =