Sha 10710-Chinese shuffle
Question Link
Question: given n cards, shuffles them n-1 times and asks if they will change back to the original sequence.
Thought: Perfect shuffling:
Suppose there is a1a2a3... anb1b2b3... BN card, set the original position of each card to X, then after a perfect shuffling, the first n cards are respectively to 2 x positions, the last n cards are respectively to 1, 3, 5 .. that is, the position of 2x % (2 n + 1). Therefore, the position of each card is 2 x % (2 * n + 1 ). in this way, the answer can be obtained by judging whether each card is in the original position, but the card cannot be determined in many cases. What should we do?
In fact, you only need to judge the first one, proving that:
Assume that the shuffles are completed P times, the first card is at 1 2 ^ P % (2 n + 1) = 1, then the position of the X card is X 2 ^ P % (2 n + 1) = x.
In consideration of this question, the perfect shuffling method given by this question can be considered as an odd number (because the first one remains unchanged) for an even number ), then, push the position change as above, and finally obtain the position of each card as x * 2 ^ (n-1) % N. In this way, 1 is entered, the problem becomes to determining 2 ^ (n-1) % N = 1, just use the quick power.
Code:
#include <stdio.h>#include <string.h>long long n;long long pow_mod(long long x, long long k, long long mod) {if (k == 0) return 1;long long ans = pow_mod(x * x % mod, k>>1, mod);if (k&1) ans = ans * x % mod;return ans;}int main() {while (~scanf("%lld", &n) && n != -1) {if (pow_mod(2, n - 1, n) == 1)printf("%d is a Jimmy-number\n", n);elseprintf("%d is not a Jimmy-number\n", n); }return 0;}