zoukankan      html  css  js  c++  java
  • 2^x mod n = 1(欧拉定理,欧拉函数,快速幂乘)

    2^x mod n = 1

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 9231    Accepted Submission(s): 2837


    Problem Description
    Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.
     
    Input
    One positive integer on each line, the value of n.
     
    Output
    If the minimum x exists, print a line with 2^x mod n = 1.

    Print 2^? mod n = 1 otherwise.

    You should replace x and n with specific numbers.
     
    思路:
    1. 当n为偶数时,bn + 1(b为整数)是奇数,而2^x是偶数,故 2^x mod n = 1不可能成立;
    2. 当n等于1时,不能成立
    3. 当n为非1的奇数时,n和2互质,由欧拉定理:若a,n为正整数,且两者互素,则a^phi(n) mod n = 1,其中phi(n)是n的欧拉函数。知2^phi(n) mod n = 1.因此phi(n)必是符合要求的x,但phi(n)未必是最小的,遍历小于其的正整数,逐一试验即可,计算2^x mod n时用快速幂乘。
     
    AC Code:
     1 #include <iostream>
     2 #include <vector>
     3 #include <cstdio>
     4 #include <algorithm>
     5 #include <cstring>
     6 using namespace std;
     7 
     8 //计算n的欧拉函数
     9 int Eular(int n)
    10 {
    11     int res = 1, i;
    12     for (i = 2; i * i <= n; i++){
    13         if (n % i == 0){
    14             n /= i;
    15             res *= (i - 1);
    16             while (n % i == 0){
    17                 n /= i;
    18                 res *= i;
    19             }
    20         }
    21     }
    22     if (n > 1) res *= (n - 1);
    23     return res;
    24 }
    25 
    26 //快速幂乘计算2^b % n
    27 int myPow(int b, int n)  
    28 {
    29     if(b == 0) return 1;
    30     long long c = myPow(b >> 1, n);
    31     c = (c * c) % n;
    32     if(b & 1) c = (2 * c) % n;
    33     return c;
    34 }
    35 
    36 int main()
    37 {
    38     int n, x;
    39     bool ok;
    40     while(scanf("%d", &n) != EOF){
    41         ok = 0;
    42         if((n & 1) && (n - 1)){
    43             ok = 1;
    44             int phi = Eular(n);
    45             for(x = 1; x < phi; x++){
    46                 if(myPow(x, n) == 1) break;
    47             }
    48         }
    49         if(ok) printf("2^%d mod %d = 1
    ", x, n);
    50         else printf("2^%? mod %d = 1
    ", n);
    51     }
    52     return 0;
    53 }

     

  • 相关阅读:
    Get distinct count of rows in the DataSet
    单引号双引号的html转义符
    PETS Public English Test System
    Code 39 basics (39条形码原理)
    Index was outside the bounds of the array ,LocalReport.Render
    Thread was being aborted Errors
    Reportviewer Error: ASP.NET session has expired
    ReportDataSource 值不在预期的范围内
    .NET/FCL 2.0在Serialization方面的增强
    Perl像C一样强大,像awk、sed等脚本描述语言一样方便。
  • 原文地址:https://www.cnblogs.com/cszlg/p/3277135.html
Copyright © 2011-2022 走看看