10710-Chinese shuffle (number theory + perfect shuffling)

Source: Internet
Author: User
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;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.